首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何扩展Java注解?

如何扩展Java注解?
EN

Stack Overflow用户
提问于 2014-03-02 19:16:31
回答 4查看 68.4K关注 0票数 50

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

代码语言:javascript
复制
@With(Secure.class)
public class Test { //....

@With的源代码

代码语言:javascript
复制
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface With { 

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

我想编写自定义注释@Secure,它将具有与@With(Secure.class)相同的效果。如何做到这一点?

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

代码语言:javascript
复制
@With(Secure.class)
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface Secure {

}
EN

回答 4

Stack Overflow用户

发布于 2014-12-11 00:46:15

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

代码语言:javascript
复制
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE})
public @interface SuperAnnotation {
    String value();
}

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

用法:

代码语言:javascript
复制
@SubAnnotation(subValue = "...", superAnnotation = @SuperAnnotation(value = "superValue"))
class someClass { ... }
票数 30
EN

Stack Overflow用户

发布于 2017-09-23 00:00:37

代码语言:javascript
复制
@With(Secure.class)
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface Secure {

}

这将会起作用。

票数 8
EN

Stack Overflow用户

发布于 2018-03-14 18:46:09

您可以像这样使用注解的注解:

代码语言:javascript
复制
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
@WithSecurityContext(factory = WithCustomUserSecurityContextFactory.class)
public @interface WithCustomUser {
  String username() default "demo@demo.com";
  String password() default "demo";
  String[] authorities() default {Authority.USER};
}

并在其“子元素”中定义确切的状态。

代码语言:javascript
复制
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
@WithCustomUser(username = "admin@admin.com",
                password = "admin",
                authorities = {Authority.USER, Authority.ADMINISTRATOR})
public @interface WithAdminUser {
}

在这种情况下,您有某种“状态”,并通过反射/方面访问父注释字段。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/22126851

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档