如何从常量 java 为注解提供值

2022-01-13 00:00:00 arrays annotations java

我认为这在 Java 中可能是不可能的,因为注解及其参数是在编译时解析的.我有一个界面如下,

I am thinking this may not be possible in Java because annotation and its parameters are resolved at compile time. I have an interface as follows,

public interface FieldValues {
   String[] FIELD1 = new String[]{"value1", "value2"};
}

和另一个类,

@SomeAnnotation(locations = {"value1", "value2"})
public class MyClass {
   ....
}

我用注释标记了许多类,我想知道是否可以避免在我更喜欢使用的每个注释中指定字符串

I mark many classes with the annotation and I would like to know if I can avoid specifying the strings in every annotation I would instead prefer to use

@SomeAnnotation(locations = FieldValues.FIELD1)
public class MyClass {
   ....
}

但是这会产生编译错误,例如注释值应该是数组初始化器等.有人知道我如何使用 String 常量或 String[] 常量来为注释提供值吗?

However this gives compilation errors like annotation value should be an array initializer etc. Does someone know how I can use a String constant or String[] constant to supply value to an annotation?

推荐答案

编译常量只能是原语和字符串:

15.28.常量表达式

编译时常量表达式是一个表达式,表示原始类型的值或不会突然完成且仅使用以下内容组成的字符串:

A compile-time constant expression is an expression denoting a value of primitive type or a String that does not complete abruptly and is composed using only the following:

  • 原始类型的文字和 String
  • 类型的文字
  • 转换为原始类型并转换为 String
  • [...] 运算符 [...]
  • 带括号的表达式,其包含的表达式是常量表达式.
  • 引用常量变量的简单名称.
  • TypeName 形式的限定名称.标识符表示常量变量.
  • Literals of primitive type and literals of type String
  • Casts to primitive types and casts to type String
  • [...] operators [...]
  • Parenthesized expressions whose contained expression is a constant expression.
  • Simple names that refer to constant variables.
  • Qualified names of the form TypeName . Identifier that refer to constant variables.

实际上在java中没有办法保护数组中的项目.在运行时,总是有人可以执行 FieldValues.FIELD1[0]=value3",因此如果我们更深入地观察,数组不可能是真正的常量.

Actually in java there is no way to protect items in an array. At runtime someone can always do FieldValues.FIELD1[0]="value3", therefore the array cannot be really constant if we look deeper.

相关文章