[英]Java: how to set default value to annotation with another annotation as its attribute?
[英]Java annotation: elements declared as method but value set as attribute
创建自定义批注时,我们将元素声明为方法,然后将值设置为属性。
例如,在这里我们声明了一个自定义注释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;
}
如果注释的属性未在接口中定义为抽象方法,则它们将成为成员。 就像是:
public @interface ComponentType {
String name;
String description;
}
但是,接口中的所有成员都是隐式的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将注释视为接口的特殊类型,因此:
像接口一样,我们只能在注释中声明最终属性:
String appName = "test application";//final attribute, never reset value
注释只能包含抽象方法(声明的方法无需实现)。
public @interface ComponentType { String name();// declared as abstract method
当我们通过注释对元素(例如类,方法,属性)进行注释时,我们需要设置这些抽象方法的返回值,这些返回方法看起来像属性,但实际上是一种实现。
@ComponentType(name = "userContainer"//set return value of method name()
我们可以通过简单地调用批注的抽象方法来使用在批注元素(例如,类,方法,属性)中设置的值。
Annotation annotation = annotatedClassObject.getAnnotation(ComponentType.class); ComponentType componentType = (ComponentType) annotation; String someName = componentType.name(); //returns value set during annotating
就像界面一样
期待更多反馈/答案
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.