俗话说温故而知新,今天又重新温习了下反射机制,java反射基本三步走
1 通过Class.forName()或者.class方法获取类对象
2 通过Method获取method对象
3 通过invoke调用对象里的方法
附:参考之前学习时候的例子代码
package utils;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class InvokeTester
{
public int add(int param1, int param2)
{
return param1 + param2;
}
public String echo(String message)
{
return "hello " + message;
}
public static void main(String[] args) throws InstantiationException, IllegalAccessException, NoSuchMethodException, SecurityException, IllegalArgumentException, InvocationTargetException {
Class<?> classType = InvokeTester.class;
Object invokeTester = classType.newInstance();
System.out.println(invokeTester instanceof InvokeTester);
Method addMethod = classType.getMethod("add", new Class[] {int.class,int.class});
Object result = addMethod.invoke(invokeTester, new Object[]{1768,2434});
System.out.println((Integer)result);
System.out.println("--------------------------");
Method echoMethod = classType.getMethod("echo", new Class[]{String.class});
Object result2 = echoMethod.invoke(invokeTester,new Object[]{"tom"});
System.out.println((String)result2);
}
}