Get the class in which the object method is implemented

I have an object objectand I will call it a method toString. How to find out in which exact class this method is implemented last?

For example, if we have a hierarchy:

class A /*extends Object */{                                                                                                              

}                                                                                                                      
class B extends A{                                                                                                              
    public String toString() {                                                                                         
        return "representation";                                                                                       
    }                                                                                                                  
}                                                                                                                      
class C extends B{                                                                                                              
}                                                                                                                      
class D extends C{                                                                                                              
}                                                                                                                      

and object

Object object = new SomeClass(); //(A/B/C/D/Object)                                                                                

then for toString()i have to get objectfor objectand A, but Bfor B, CandD

+4
source share
1 answer

You can use the method Method.getDeclaringClass():

...
private Class<?> definingClass(Class<?> clz, String method) throws NoSuchMethodException, SecurityException {
    Method m = clz.getMethod(method);
    return m.getDeclaringClass();
}

...

System.err.println(definingClass(A.class, "toString"));
System.err.println(definingClass(B.class, "toString"));
System.err.println(definingClass(C.class, "toString"));
System.err.println(definingClass(D.class, "toString"));

...

Result:

class java.lang.Object
class com.example.B
class com.example.B
class com.example.B

You need to extend the method definingClass()if you need to look for methods that have parameters.

+6
source

All Articles