import java.lang.reflect.*;
public class InvokeTester{
public int add(int param1, int param2) {
return param1 + param2;
}
public String echo(String msg) {
return "echo:" + msg;
}
public static void main(String[] args) throws Exception {
Class classType = InvokeTester.class;
Object invokeTester = classType.newInstance();
// 调用InvokeTester对象的add()方法
Method addMethod = classType.getMethod("add", new Class[] { int.class, int.class });
Object result = addMethod.invoke(invokeTester, new Object[] { new Integer(100), new Integer(200) }); System.out.println((Integer) result);
// 调用InvokeTester对象的echo()方法
Method echoMethod = classType.getMethod("echo", new Class[] { String.class });
result = echoMethod.invoke(invokeTester, new Object[] { "Hello" });
System.out.println((String) result); } }
本文通过一个具体例子展示了如何使用Java的反射机制来调用对象的方法。包括如何获取类对象、实例化对象、查找方法并调用等关键步骤。
1789

被折叠的 条评论
为什么被折叠?



