問題描述
我認為這在 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.
這篇關于如何從常量 java 為注解提供值的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!