gpt4 book ai didi

java - 如何扩展Java注解?

转载 作者:IT老高 更新时间:2023-10-28 21:14:47 25 4
gpt4 key购买 nike

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

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

@With的源码:

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

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

我想写自定义注解@Secure,效果和@With(Secure.class)一样。该怎么做?


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

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

}

最佳答案

正如 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 { ... }

关于java - 如何扩展Java注解?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22126851/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com