自 2025 年 3 月 27 日起,我们建议您使用 android-latest-release
而非 aosp-main
构建 AOSP 并为其做出贡献。如需了解详情,请参阅 AOSP 的变更。
导出常量
使用集合让一切井井有条
根据您的偏好保存内容并对其进行分类。
在接口不兼容 Java(例如由于使用联合类型而不兼容 Java)的情况下,可能仍需将常量(枚举值)导出到 Java 环境。这种情况需要用到 hidl-gen -Ljava-constants
…
,它会将已添加注解的枚举声明从软件包的接口文件中提取出来,并生成一个名为 [PACKAGE-NAME]-V[PACKAGE-VERSION]-java-constants
的 java 库。请为每个要导出的枚举声明添加注解,如下所示:
@export
enum Foo : int32_t {
SOME_VALUE,
SOME_OTHER_VALUE,
};
如有必要,这一类型导出到 Java 环境时所使用的名称可以不同于接口声明中选定的名称,方法是添加注解参数 name
:
@export(name="JavaFoo")
enum Foo : int32_t {
SOME_VALUE,
SOME_OTHER_VALUE,
};
如果依据 Java 惯例或个人偏好需要将一个公共前缀添加到枚举类型的值,请使用注解参数 value_prefix
:
// File "types.hal".
package android.hardware.bar@1.0;
@export(name="JavaFoo", value_prefix="JAVA_")
enum Foo : int32_t {
SOME_VALUE,
SOME_OTHER_VALUE,
};
生成的 Java 类如下所示:
package android.hardware.bar.V1_0;
public class Constants {
public final class JavaFoo {
public static final int JAVA_SOME_VALUE = 0;
public static final int JAVA_SOME_OTHER_VALUE = 1;
};
};
最后,针对 types.hal
中声明的枚举类型的 Java 类型声明将划分到给定软件包中的类 Constants
内。声明为接口子级的枚举类型将划分到该接口的 Java 类声明下。
本页面上的内容和代码示例受内容许可部分所述许可的限制。Java 和 OpenJDK 是 Oracle 和/或其关联公司的注册商标。
最后更新时间 (UTC):2025-07-27。
[null,null,["最后更新时间 (UTC):2025-07-27。"],[],[],null,["# Export constants\n\nIn cases where an interface isn't Java-compatible (because it uses unions\nfor example) it might still be desirable to export the constants (enum values) to\nthe Java world. This scenario is supported by `hidl-gen -Ljava-constants\n...` which extracts annotated enum declarations from the interface\nfile(s) in a package and produces a java library named\n`[PACKAGE-NAME]-V[PACKAGE-VERSION]-java-constants`. Annotate each\nenum declaration to be exported as follows: \n\n```java\n@export\nenum Foo : int32_t {\n SOME_VALUE,\n SOME_OTHER_VALUE,\n};\n```\n\nIf necessary, the name under which this type is exported to the Java world\ncan be different from that chosen in the interface declaration by adding the\nannotation-parameter `name`: \n\n```java\n@export(name=\"JavaFoo\")\nenum Foo : int32_t {\n SOME_VALUE,\n SOME_OTHER_VALUE,\n};\n```\n\nIf Java conventions or personal preference ask for a common prefix to be\nadded to the enum type's values, use the annotation-parameter\n`value_prefix`: \n\n```java\n// File \"types.hal\".\n\npackage android.hardware.bar@1.0;\n\n@export(name=\"JavaFoo\", value_prefix=\"JAVA_\")\nenum Foo : int32_t {\n SOME_VALUE,\n SOME_OTHER_VALUE,\n};\n```\n\nThe resulting Java class appears as follows: \n\n```java\npackage android.hardware.bar.V1_0;\n\npublic class Constants {\n public final class JavaFoo {\n public static final int JAVA_SOME_VALUE = 0;\n public static final int JAVA_SOME_OTHER_VALUE = 1;\n };\n};\n```\n\nFinally, Java type declaration for enum types declared in\n`types.hal` are grouped inside a class `Constants` in the\ngiven package. Enum types declared as children of an interface are grouped\nunder that interface's Java class declaration."]]