自定义注解参数化继承其他注解
custom annotation parametrized inherit other annotation
我有一个参数化注释(在本例中为 @MiTag1
)。我想创建一个新的注释 (@MiTag2
),它扩展了 @MiTag1
和其他注释,我希望 @MiTag1
"be extended" 的值等于 @MiTag2
在我的代码示例中,@MiTag2("bla")
必须与 @MiTag1("bla")
相同,但 @MiTag2
中没有硬编码 "bla"。
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface MiTag1 {
/**
* The resource key.
*
* @see Resources
*/
String value();
}
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@MiTag1(value = THIS.VALUE)
public @interface MiTag2 {
/**
* The resource key.
*
* @see Resources
*/
String value();
}
Java 不允许您从另一个注释进行扩展。这是设计使然,因为它会引入相当复杂的类型系统。这个问题已经详细回答了here,但重要的部分是:
Why don’t you support annotation subtyping (where one annotation type
extends another)?
It complicates the annotation type system, and makes it much more
difficult to write “Specific Tools”.
…
“Specific Tools” — Programs that query known annotation types of
arbitrary external programs. Stub generators, for example, fall into
this category. These programs will read annotated classes without
loading them into the virtual machine, but will load annotation
interfaces.
(来自 pedromarce 的原始答案)
要绕过这个问题,您可以使用两个注释来注释您的目标类型
@MiTag1 @MiTag2
并将 should inheriting 注解的默认值设置为 parent 注解.
的值
此外,您可以使用组合而不是继承,并将 @MiTag2
类型的注释添加到 @MiTag2
。
我有一个参数化注释(在本例中为 @MiTag1
)。我想创建一个新的注释 (@MiTag2
),它扩展了 @MiTag1
和其他注释,我希望 @MiTag1
"be extended" 的值等于 @MiTag2
在我的代码示例中,@MiTag2("bla")
必须与 @MiTag1("bla")
相同,但 @MiTag2
中没有硬编码 "bla"。
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface MiTag1 {
/**
* The resource key.
*
* @see Resources
*/
String value();
}
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@MiTag1(value = THIS.VALUE)
public @interface MiTag2 {
/**
* The resource key.
*
* @see Resources
*/
String value();
}
Java 不允许您从另一个注释进行扩展。这是设计使然,因为它会引入相当复杂的类型系统。这个问题已经详细回答了here,但重要的部分是:
Why don’t you support annotation subtyping (where one annotation type extends another)?
It complicates the annotation type system, and makes it much more difficult to write “Specific Tools”.
…
“Specific Tools” — Programs that query known annotation types of arbitrary external programs. Stub generators, for example, fall into this category. These programs will read annotated classes without loading them into the virtual machine, but will load annotation interfaces.
(来自 pedromarce 的原始答案)
要绕过这个问题,您可以使用两个注释来注释您的目标类型
@MiTag1 @MiTag2
并将 should inheriting 注解的默认值设置为 parent 注解.
此外,您可以使用组合而不是继承,并将 @MiTag2
类型的注释添加到 @MiTag2
。