gpt4 book ai didi

java - 如何从常量 java 为注释提供值

转载 作者:行者123 更新时间:2023-12-02 00:47:04 26 4
gpt4 key购买 nike

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

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

和另一个类,

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

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

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

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

最佳答案

编译常量can only be primitives and Strings :

15.28. Constant Expressions

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:

  • 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" 操作,因此,如果我们深入研究,该数组不可能是真正的常量。

关于java - 如何从常量 java 为注释提供值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57888065/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com