我认为这在 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
String
String
实际上在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.
这篇关于如何从常量 java 为注解提供值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!