MethodInvoker.java
public class MethodInvoker {
public static final VoidType VOID = new VoidType();
private static Method validate(Object targetObject, String targetMethod, Object[] arguments) throws ClassNotFoundException, NoSuchMethodException
{
if (targetObject == null) {
throw new IllegalArgumentException("Either targetClass or targetObject is required");
}
if (targetMethod == null) {
throw new IllegalArgumentException("targetMethod is required");
}
if (arguments == null) {
arguments = new Object[0];
}
Class[] types = new Class[arguments.length];
for (int i = 0; i < arguments.length; ++i) {
types[i] = arguments[i].getClass();
}
// try to get the exact method first
Class targetClass = targetObject.getClass();
Method methodObject = null;
try {
methodObject = targetClass.getMethod(targetMethod, types);
}
catch (NoSuchMethodException ex) {
int matches = 0;
Method[] methods = targetClass.getMethods();
for (int i = 0; i < methods.length; ++i) {
Method method = methods[i];
if (method.getName().equals(targetMethod) && method.getParameterTypes().length == types.length) {
methodObject = method;
++matches;
}
}
// just rethrow exception if we can't get a match
if (methodObject == null || matches > 1) {
throw ex;
}
}
return methodObject;
}
public static Object invoke(Object clazz,String methodName,Object[] args) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException {
Method methodObject = null;
Object result = null;
try{
methodObject = validate(clazz, methodName, args);
}
catch(NoSuchMethodException ex){
throw ex;
}
catch(ClassNotFoundException e){
throw e;
}
if (Modifier.isStatic(methodObject.getModifiers())) {
result = methodObject.invoke(null, args);
}
else{
result = methodObject.invoke(clazz, args);
}
return (result == null ? VOID : result);
}
} |