问题描述
我想这可能不是在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 {
....
}
我标志着许多类的注解,我想知道如果我能避免在每一个注释指明我反而preFER使用字符串
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 {
....
}
像注释值
然而,这给了编译错误,应该是一个数组初始化程序等是否有人知道如何可以使用字符串常量或字符串[]不断提供价值注释?
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。恒前pressions
一个编译时的恒前pression 的是前pression表示基本类型或一个字符串的值不会突然完成,并且只使用以下组成:
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:
- 原始类型的文字和类型的文字
字符串
- 强制转换为原始类型及管键入
字符串
- [...]运营商[...]
- 括号前pressions其所含的前pression是一个不断前pression。
- 引用常量变量简单的名称。
- 形式限定名称的类型名的。的标识的引用变量不变。
- 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] =值3
,所以阵列不能,如果我们再深入真正不变的。
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的恒定值提供一个注解的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!