Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get class in which method of object is implemented

I have an object object and I'm going to call it's method toString. How do I know in what exact class this method is implemented last?

For example if we have hierarchy:

class A /*extends Object */{                                                                                                              

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

and the object

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

then for toString() I should get Object for Object and A but B for B, C and D

like image 885
RiaD Avatar asked Mar 18 '23 19:03

RiaD


1 Answers

You can use the Method.getDeclaringClass() method:

...
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 definingClass() method appropriately if you need to look up methods which have parameters.

like image 127
Andreas Fester Avatar answered Apr 02 '23 07:04

Andreas Fester