JAVA 反射方式执行类方法
public class ReflectTest {
@Test
public void test() {
try {
Object object = invoke("java.text.SimpleDateFormat", "format", new Date());
System.out.println(object);
} catch (Exception e) {
e.printStackTrace();
}
}
public Object invoke(String className, String methodName, Object... args) throws Exception {
// 根据全类名实例化对象
Object object = Class.forName(className).newInstance();
return invoke(object, methodName, args);
}
public Object invoke(Object object, String methodName, Object... args) throws Exception {
// 获取要执行方法的参数类型
Class[] parameterTypes = new Class[args.length];
for (int i = 0; i < args.length; i++) {
parameterTypes[i] = args[i].getClass();
}
// 获取方法(包括父类的,但不能获取私有方法)
Method method = object.getClass().getMethod(methodName, parameterTypes);
// 执行方法
return method.invoke(object, args);
}
}