您的位置:首页 > 编程语言 > Java开发

一个小java反射程序,简单的调用方法。

2011-01-17 18:04 597 查看
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);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐