如何从常量 java 为注释提供值 [英] How to supply value to an annotation from a Constant java

查看:23
本文介绍了如何从常量 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.

这篇关于如何从常量 java 为注释提供值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆