2014-03-02 113 views
18

在项目中,我使用预先定义的注释@With如何扩展Java注释?

@With(Secure.class) 
public class Test { //.... 

@With的源代码:

@Retention(RetentionPolicy.RUNTIME) 
@Target(ElementType.TYPE) 
public @interface With { 

    Class<?>[] value() default {}; 
} 

我想编写自定义注释@Secure,它会自动将Secure.class@With注解。怎么做?


如果我这样做?它会起作用吗?

@With(Secure.class) 
@Target({ElementType.TYPE}) 
@Retention(RetentionPolicy.RUNTIME) 
public @interface Secure { 

} 

回答

11

从Java语言规范,Chapter 9.6 Annotation Types

没有扩展条款是允许的。 (注释类型隐式扩展为annotation.Annotation。)

因此,不能扩展注释。您需要使用其他一些机制或创建一个识别和处理您自己的注释的代码。 Spring允许您在自己的自定义注释中对其他Spring的注释进行分组。但仍然没有延伸。

+0

可能'扩展'并不是最好的表达。我的意思是实施自动放置参数。 – bvitaliyg

+0

@bvitaliyg:您可以使用任何默认字段创建自己的注释,但是jvm中没有可以自动识别它的开箱即用机制。您需要自己编写该代码或检查现有库(如spring)是否足以满足您的需求 – piotrek

+0

这不是Spring框架。 – bvitaliyg

9

正如piotrek所指出的那样,您不能在继承的意义上扩展Annotations。不过,你可以创建一个聚集他人注解:

@Retention(RetentionPolicy.RUNTIME) 
@Target({ElementType.TYPE}) 
public @interface SuperAnnotation { 
    String value(); 
} 

@Retention(RetentionPolicy.RUNTIME) 
@Target({ElementType.TYPE}) 
public @interface SubAnnotation { 
    SuperAnnotation superAnnotation(); 
    String subValue(); 
} 

用法:

@SubAnnotation(subValue = "...", superAnnotation = @SuperAnnotation(value = "superValue")) 
class someClass { ... } 
0

如何制作Secure标注有默认value()

@Retention(RetentionPolicy.RUNTIME) 
@Target(ElementType.TYPE) 
public @interface Secure { 

    Class<?>[] value() default { Secure.class }; 
} 
0
@With(Secure.class) 
@Target({ElementType.TYPE}) 
@Retention(RetentionPolicy.RUNTIME) 
public @interface Secure { 

} 

这将工作。

+0

这是直接从问题中直接复制。 – mkobit

+0

@mkobit斑点。由于提问者询问这是否适用于他们的问题,我的回答就直截了当地回答了问题。 –

0

为了扩展穆罕默德·阿卜杜勒 - 拉赫曼的answer--

@With(Secure.class) 
@Target({ElementType.TYPE}) 
@Retention(RetentionPolicy.RUNTIME) 
public @interface Secure { 

} 

这确实默认的工作,但你可以结合Spring的AnnotationUtils使用它。

查看this SO answer举例。