, , ( , , ), . , , , ( , , ). , Object. , , , .
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class TestParent {
public static void main(String[] args) {
System.out.println(getParents(Class3.class, "doSomething"));
System.out.println(getParents(Class3.class, "run"));
}
private static List<Class> getParents(Class<?> type, String methodName) {
Method method = getMethodByName(type, methodName);
if (method == null)
return Collections.emptyList();
Class nextClass = type.getSuperclass();
Class parent = null;
while (!nextClass.equals(Object.class)) {
if (hasMethod(nextClass, methodName, method)) {
parent = nextClass;
}
nextClass = nextClass.getSuperclass();
}
List<Class> parents = new ArrayList<>();
if (parent != null) {
for (Class t : parent.getInterfaces()) {
if (hasMethod(t, methodName, method)) {
parents.add(t);
}
}
if (parents.isEmpty())
parents.add(parent);
} else {
for (Class t : type.getInterfaces()) {
if (hasMethod(t, methodName, method)) {
parents.add(t);
}
}
}
return parents;
}
private static boolean equalMethod(Method m1, Method m2) {
return m1.getName().equals(m2.getName()) && m1.getReturnType().equals(m2.getReturnType());
}
private static boolean hasMethod(Class<?> type, String methodName, Method method) {
Method m = getMethodByName(type, methodName);
return m != null && equalMethod(method, m);
}
private static Method getMethodByName(Class<?> type, String methodName) {
for (Method m : type.getDeclaredMethods()) {
if (m.getName().equals(methodName)) {
return m;
}
}
return null;
}
public interface Class1<O> {
void doSomething(O s);
}
public interface Class2 {
void doSomething(String s);
}
public class Class3 extends Class4 implements Class1<String>, Class2 {
public void doSomething(String s) {
}
@Override
void run() {
}
}
public abstract class Class4 extends Class5 {
abstract void run();
}
public abstract class Class5 {
abstract void run();
}
}