当我们创建自定义注释时,我们将元素声明为方法,然后将值设置为属性。
例如,这里我们声明了一个自定义注释ComponentType
,其元素name()
和description()
看起来像方法。
public @interface ComponentType {
String name();// declared as method
String description();
}
当使用注释时,它们如下所示:
@ComponentType(name = "userContainer", // value looks like an attribute
description = "a user container")
public class UserEntity { }
我的问题是:为什么 Java 不允许像这样将元素声明为属性?
public @interface ComponentType {
String name; // Compilation Error
String description;
}
最佳答案
如果注释的属性没有定义为接口(interface)中的抽象方法,那么它们将是成员。像这样的东西:
public @interface ComponentType {
String name;
String description;
}
但是,接口(interface)中的所有成员都隐式地是 final
(和 static
),并且上述代码无法编译,因为 name
和description
未初始化。
但是如果它们实际上是用一些值初始化的:
public @interface ComponentType {
String name = "name";
String description = "description";
}
那么像下面这样的片段是不可能的:
@ComponentType(
name = "userContainer" //cannot assign a value to a final variable
, description = "a user container")
关于Java注释: elements declared as method but value set as attribute,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35550862/