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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With