Java注释: elements declared as method but value set as attribute

标签 java annotations

当我们创建自定义注释时,我们将元素声明为方法,然后将值设置为属性。

例如,这里我们声明了一个自定义注释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),并且上述代码无法编译,因为 namedescription 未初始化。

但是如果它们实际上是用一些值初始化的:

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/

相关文章:

java - 注释怎么可能是对自身的注释?

java - 指定在 ObjectOutputStream 中(不)序列化哪些字段而不使用 transient 或 serialPersistentFields

java - Listview删除项目和刷新 - android

java - Spring @Autowired - 后台发生了什么

annotations - 使用 MASI 距离的 NLTK 协议(protocol)的低 alpha

注释和静态 block 的java处理顺序

java - 如何在自定义适配器 Android Studio Java 中将标签设置为行

java.sql.SQLException : Could not set parameter at position 1 (values was 1) using jdbc. queryForObject

java - 如何减少 spring boot Controller 中的重复代码

ios - 拖动注释时的回调