2

I need to check, form super class, if derived class have a specific annotation:

public class SuperClass
{
  public boolean hasAnnotation()
  {
    //super_class_method_code
  }
}

@annotationToCheck
public class DerivedClass extends SuperClass
{
   //derived_class_code
}

It is possible in Java? I know how to do in C# but in Java I can't find any solution... :(

Thank you!!!

Pshemo
  • 122,468
  • 25
  • 185
  • 269
Gerard Llort
  • 47
  • 2
  • 8
  • 1
    This is the solution in C#: http://stackoverflow.com/questions/10605884/access-on-attribute-of-extended-class-from-superclass/10605907#10605907 – Gerard Llort Dec 13 '12 at 11:16
  • [may this help][1] [1]: http://stackoverflow.com/questions/3504870/how-to-test-if-one-java-class-extends- another-at-runtime – Sajid Hussain Dec 13 '12 at 11:23

2 Answers2

10

If your instance is actually of the subclass type, this is as easy as defining the method in the supertype to have the following implementation:

this.getClass().isAnnotationPresent(annotationToCheck.class);

As the this is an instance of DerivedClass, the getClass returns DerivedClass and the check works.

Note2: As @Pshemo mentions in the comments, this only works when the annotation is annotated with @Retention(RetentionPolicy.RUNTIME).

Hiery Nomus
  • 17,429
  • 2
  • 41
  • 37
  • 2
    +1 I will just add that this works for annotations with `@Retention(RetentionPolicy.RUNTIME)` policy. – Pshemo Dec 13 '12 at 11:44
  • Ohhhhh!!!! I forgot specify @Retention( value = RetentionPolicy.RUNTIME ) and @Target( value = ElementType.TYPE) in my annotation!!! THANK YOU Hiery and Pshemo!!! – Gerard Llort Dec 13 '12 at 11:44
  • @Pshemo Good observation! Thanks for adding that. – Hiery Nomus Dec 13 '12 at 12:43
  • Feel free to update you answer with this info or upvote my comment to make it more visible (for people who - like me at the begining - ware wondering why it is not working for them :) – Pshemo Dec 13 '12 at 12:54
  • @HieryNomus I removed () from class declarations in OP question so Note 1 is pointless now (sorry ;p) – Pshemo Dec 13 '12 at 17:02
0

Another way of getting derived classes using reflections project. This reflections project has dependencies( slf4j,log4j and javassist etc).


Note: Derived classes should be in mentioned package only.

import java.util.Set;

import org.reflections.Reflections;

public class Base {

    public Base() {
        Reflections reflections = new Reflections("com.sree.despacerivedclasskage");
        Set<Class<? extends Base>> classes = reflections
                .getSubTypesOf(Base.class);
        System.out.println(classes);
        for(Class clazz: classes){
            System.out.println(clazz.isAnnotationPresent(ToCheck.class));
        }

    }
public static void main(String[] args) {
    Base b = new Base();
}

}