package com.ygl.reflect;标签:反射,int,Auto,clazz,printStackTrace,catch,class From: https://blog.51cto.com/u_10028442/5824671
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class InvokeTest {
public int add(int param1,int parma2){
return param1+parma2;
}
public String echo(String msg){
return msg;
}
public static void main(String[] args) throws IllegalArgumentException, InvocationTargetException {
Class<?> clazz=InvokeTest.class;//或Class<?> clazz=Class.forName("com.ygl.reflect.InvokeTest");
try {
Object invokeTest=clazz.newInstance();
try {
//参数所对应的class对象组成的数组,区分重载方法
Method addMethod=clazz.getMethod("add", new Class[]{int.class,int.class});
//相应方法对象-->调用具体实例(invokeTest)
Object result=addMethod.invoke(invokeTest, new Object[]{1,2});
System.out.println(result);
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}