动态执行当前类或其父类的方法,支持私有方法。
public <E> E invoke (Object obj, String methodName, Object... args) throws Exception {
Class cls = obj.getClass();Class[] paramTypes = new Class[args.length];
for (int i = 0; i < args.length; i++) {paramTypes[i] = args[i].getClass();
}
Method method = getMethod(cls, methodName, paramTypes);
method.setAccessible(true); //允许调用私有方法
return (E)method.invoke(obj, args);
}
Object obj = Class.forName(clsName).newInstance();
return invoke(obj, methodName, args);}
private Method getMethod(Class cls, String methodName, Class[] paramsType) {
for (; cls != Object.class; cls = cls.getSuperclass()) {
try {
Method method = cls.getDeclaredMethod(methodName, paramsType);
return method;
} catch (Exception e) {
continue;
}
}
return null;
}