如何扩展Java注释? [英] How to extend Java annotation?
问题描述
在项目中,我使用pre定义的注释 @With
:
@With(Secure.class)
公共类的测试{// ....
的源$ C $ C @With
:
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
公共@interface随着{ 类<> []值()默认{};
}
我要编写自定义批注 @Secure
,它会自动将 Secure.class
到 @With
注释。那怎么办?
如果我做的这样吗?将它的工作?
@With(Secure.class)
@Target({} ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
公共@interface安全{}
从Java语言规范,的第9.6节注释类型的:
没有extends子句是允许的。 (译注类型都隐延长
annotation.Annotation
)
块引用>所以,你不能扩展的一种诠释。你需要使用一些其他机制或创建一个code的识别和处理自己的注释。 Spring允许你组其他Spring的注解在自己的自定义注释。但仍然没有延长。
In my project I use pre-defined annotation
@With
:@With(Secure.class) public class Test { //....
The source code of
@With
:@Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) public @interface With { Class<?>[] value() default {}; }
I want to write custom annotation
@Secure
, which will automatically placeSecure.class
to@With
annotation. How to do that?
What if I do like this? Will it work?
@With(Secure.class) @Target({ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) public @interface Secure { }
解决方案From Java language specification, Chapter 9.6 Annotation Types:
No extends clause is permitted. (Annotation types implicitly extend
annotation.Annotation
.)So, you can not extend an Annotation. you need to use some other mechanism or create a code that recognize and process your own annotation. Spring allows you to group other Spring's annotation in your own custom annotations. but still, no extending.
这篇关于如何扩展Java注释?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!