If you know the type is List
, then use List.class
as argument.
If you don't know the type in advance, imagine you have:
public void m(List l) {
// all lists
}
public void m(ArrayList l) {
// only array lists
}
Which method should the reflection invoke, if there is any automatic way?
If you want, you can use Class.getInterfaces()
or Class.getSuperclass()
but this is case-specific.
What you can do here is:
public void invoke(Object targetObject, Object[] parameters,
String methodName) {
for (Method method : targetObject.getClass().getMethods()) {
if (!method.getName().equals(methodName)) {
continue;
}
Class<?>[] parameterTypes = method.getParameterTypes();
boolean matches = true;
for (int i = 0; i < parameterTypes.length; i++) {
if (!parameterTypes[i].isAssignableFrom(parameters[i]
.getClass())) {
matches = false;
break;
}
}
if (matches) {
// obtain a Class[] based on the passed arguments as Object[]
method.invoke(targetObject, parametersClasses);
}
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…