RiaD
RiaD

Reputation: 47619

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

Upvotes: 5

Views: 3296

Answers (1)

Andreas Fester
Andreas Fester

Reputation: 36630

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.

Upvotes: 8

Related Questions