在我的项目中,我使用了预定义的注释@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 {
}
发布于 2014-12-11 00:46:15
正如piotrek所指出的,您不能从继承的意义上扩展注释。不过,您仍然可以创建聚合其他注释的注释:
@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 { ... }
发布于 2017-09-23 00:00:37
@With(Secure.class)
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface Secure {
}
这将会起作用。
发布于 2018-03-14 18:46:09
您可以像这样使用注解的注解:
@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};
}
并在其“子元素”中定义确切的状态。
@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 {
}
在这种情况下,您有某种“状态”,并通过反射/方面访问父注释字段。
https://stackoverflow.com/questions/22126851
复制相似问题