Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Check if Annotation is inherited

I have an annotation and three classes like this:

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

Is there any way I can determine if a present annotation is inherited or declared directly at the class?

Something like a method public boolean isInherited(Class<?> clazz, MyAnnotation annotation) that should only be called if the annotation is present.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Exptected output:

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

>Solution :

You can use getDeclaredAnnotation instead of getAnnotation:

public boolean isInherited(Class<?> clazz, Class<? extends Annotation> annotation) {
    return clazz.isAnnotationPresent(annotation) && clazz.getDeclaredAnnotation(annotation) == null;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading