检查Annotation是否被继承
Check if Annotation is inherited
我有一个注释和三个 class这样的:
@Inherited
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {}
@MyAnnotation
public class MySuperClass {}
public class MySubClassA extends MySuperClass {}
@MyAnnotation
public class MySubClassB extends MySuperClass {}
有什么方法可以确定当前注释是继承的还是直接在 class 处声明的?
类似方法 public boolean isInherited(Class<?> clazz, MyAnnotation annotation)
的东西,只有在注释存在时才应调用。
预期输出:
isInherited(MySuperClass.class, MySuperClass.class.getAnnotation(MyAnnotation.class)) --> false
isInherited(MySubClassA.class, MySubClassA.class.getAnnotation(MyAnnotation.class)) --> true
isInherited(MySubClassB.class, MySubClassB.class.getAnnotation(MyAnnotation.class)) --> false
您可以使用 getDeclaredAnnotation
代替 getAnnotation
:
public boolean isInherited(Class<?> clazz, Class<? extends Annotation> annotation) {
return clazz.isAnnotationPresent(annotation) && clazz.getDeclaredAnnotation(annotation) == null;
}
我有一个注释和三个 class这样的:
@Inherited
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {}
@MyAnnotation
public class MySuperClass {}
public class MySubClassA extends MySuperClass {}
@MyAnnotation
public class MySubClassB extends MySuperClass {}
有什么方法可以确定当前注释是继承的还是直接在 class 处声明的?
类似方法 public boolean isInherited(Class<?> clazz, MyAnnotation annotation)
的东西,只有在注释存在时才应调用。
预期输出:
isInherited(MySuperClass.class, MySuperClass.class.getAnnotation(MyAnnotation.class)) --> false
isInherited(MySubClassA.class, MySubClassA.class.getAnnotation(MyAnnotation.class)) --> true
isInherited(MySubClassB.class, MySubClassB.class.getAnnotation(MyAnnotation.class)) --> false
您可以使用 getDeclaredAnnotation
代替 getAnnotation
:
public boolean isInherited(Class<?> clazz, Class<? extends Annotation> annotation) {
return clazz.isAnnotationPresent(annotation) && clazz.getDeclaredAnnotation(annotation) == null;
}