Search Method
import java.lang.reflect.Method;
import java.util.HashSet;
import java.util.Set;
public abstract class ClassUtils {
static public Method searchMethod(Method[] methods, String methodName,
Class<?>... paramType) {
if (methods == null || methods.length == 0)
return null;
for (Method method : methods) {
Class<?>[] m = method.getParameterTypes();
if (methods.length == 1 && m.length == 0) {
return method;
} else if (m.length == paramType.length) {
for (int i = 0; i < paramType.length; i++) {
if (m[i].equals(paramType[i])) {
return method;
}
}
}
}
return null;
}
static public <T> Method getMethod(Class<T> type, String methodName,
Class<?>... params) {
if (type != null && methodName != null && methodName.length() > 0) {
try {
if (params != null && params.length > 0 && params[0] != null) {
return type.getMethod(methodName, params);
} else {
return type.getMethod(methodName);
}
} catch (NoSuchMethodException e) {
}
}
return null;
}
static Set<Class<?>> getAllClasses(Set<Class<?>> classes, Class<?> type) {
Class<?>[] list = type.getClasses();
for (Class<?> t : list) {
classes = getAllClasses(classes, t);
classes.add(t);
}
Class<?>[] interfaces = type.getInterfaces();
for (Class<?> t : interfaces) {
classes = getAllClasses(classes, t);
classes.add(t);
}
Class<?> superClass = type.getSuperclass();
if (superClass != null && superClass != Object.class) {
Set<Class<?>> superClasses = getAllClasses(classes, superClass);
for (Class<?> t : superClasses) {
classes = getAllClasses(classes, t);
classes.add(t);
}
}
return classes;
}
static public Method searchMethod(Class<?> type, String methodName,
Class<?>... paramType) {
Method m = paramType.length > 0 && paramType[0] != null ? getMethod(
type, methodName, paramType) : getMethod(type, methodName);
if (m != null)
return m;
// paramType is interface?
if (paramType != null && paramType.length > 0 && paramType[0] != null) {
Set<Class<?>> p = getAllClasses(new HashSet<Class<?>>(),
paramType[0]);
// Class<?>[] p = paramType[0].getDeclaredClasses();
if (p != null) {
for (Class<?> refIF : p) {
m = getMethod(type, methodName, refIF);
if (m != null)
return m;
}
}
// paramType is Object.class
Class<?>[] argsType = new Class<?>[paramType.length];
for (int i = 0; i < paramType.length; i++) {
argsType[i] = Object.class;
}
m = getMethod(type, methodName, argsType);
}
return m;
}
}
Related examples in the same category