lundi 6 mars 2017

Reflection: Get subclass of inherited Method

I have provided instance of Method, and based on it I'm trying to gather meta information about class of object invoking it.

However if method is inherited from some Base class, only original method class is returned. I would want know from which subclass object invoked it.

Code better than 1000 words:

public class TestReflection {
    public static void main(String[] args) throws NoSuchMethodException {
        Method method = SubClass.class.getMethod("doSomething");
        String className = method.getDeclaringClass().getName();

        System.out.println(className); // prints Base, but I want SubClass
    }
}

class SubClass extends Base {}

class Base {
    public void doSomething() {}
}

Why I want to distinquish subclass and base class?

  • I'm using TestNG framework, and many test classes extends Base abstract Test providing some additional information.
  • TestNG calls listener, that pass Method instance of runned Test. Based on that, I want to check which annotations are set on specific subclass.




Aucun commentaire:

Enregistrer un commentaire