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.
source
share