如何扩展Java注解? [英] How to extend Java annotation?

查看:32
本文介绍了如何扩展Java注解?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的项目中,我使用预定义的注释 @With:

In my project I use pre-defined annotation @With:

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

@With的源码:

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

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

我想写自定义注解@Secure,效果和@With(Secure.class)一样.如何做到这一点?

I want to write custom annotation @Secure, which will have the same effect as @With(Secure.class). 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 {

}

推荐答案

正如 piotrek 所指出的,您不能在继承的意义上扩展 Annotations.不过,您可以创建聚合其他注释的注释:

As piotrek pointed out, you cannot extend Annotations in the sense of inheritance. Still, you can create Annotations that aggregate others:

@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 { ... }

这篇关于如何扩展Java注解?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆