import java.lang.reflect.Method;
@SuppressWarnings("rawtypes")
public class ReflectionUtil {
@SuppressWarnings("unchecked")
public static Object invokeStaticMethod(String className, String methodName, Object[] args) throws Exception {
Class ownerClass = Class.forName(className);
Method tMethod = null;
tMethod = getMethod(ownerClass, methodName, args);
if (tMethod == null) {
Class[] argsClass = new Class[args.length];
int i = 0;
for (int j = args.length; i < j; i++) {
argsClass[i] = args[i].getClass();
}
tMethod = ownerClass.getMethod(methodName, argsClass);
}
return tMethod.invoke(null, args);
}
/***
* reflection invoke method
* @param className
* @param methodName
* @param args
* @return
* @throws Exception
*/
@SuppressWarnings("unchecked")
public static Object invokeMethod(String className, String methodName, Object[] args) throws Exception {
Class ownerClass = Class.forName(className);
Method tMethod = null;
tMethod = getMethod(ownerClass, methodName, args);
if (tMethod == null) {
Class[] argsClass = new Class[args.length];
int i = 0;
for (int j = args.length; i < j; i++) {
argsClass[i] = args[i].getClass();
}
tMethod = ownerClass.getMethod(methodName, argsClass);
}
return tMethod.invoke(ownerClass.newInstance(), args);
}
private static Method getMethod(Class clazz, String methodName, Object[] args) {
Method[] methods = clazz.getMethods();
Method m = null;
for (Method method : methods) {
if (method.getName().equals(methodName)) {
Class[] parameterTypes = method.getParameterTypes();
if (method.getParameterTypes().length == args.length) {
for (int i = 0; i < parameterTypes.length; i++) {
if (! parameterTypes[i].isInstance(args[i])) {
break;
}
m = method;
}
}
}
}
return m;
}
}