[Java] - 通过反射调用对象的方法

来源:http://user.qzone.qq.com/31584 (QQ空间)

        http://b.qzone.qq.com/cgi-bin/blognew/blog_output_data?uin=31584&blogid=1270205768&styledm=qzonestyle.gtimg.cn&imgdm=qzs.qq.com&bdm=b.qzone.qq.com&mode=2&numperpage=15&blogseed=0.7275722332481711&property=GoRE&timestamp=1273108498 (实际地址)

 

 TestRef.java

import java.lang.reflect.Method;
import java.lang.reflect.InvocationTargetException;

/**
* Created by IntelliJ IDEA.
* File: TestRef.java
* User: String
* Date: 2010-3-29 14:48:44
*/
public class TestRef {

public static void main(String args[]) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
Foo foo
= new Foo("这个一个Foo对象!");
Class clazz
= foo.getClass();
Method m1
= clazz.getDeclaredMethod("outInfo");
Method m2
= clazz.getDeclaredMethod("setMsg", String.class);
Method m3
= clazz.getDeclaredMethod("getMsg");
m1.invoke(foo);
m2.invoke(foo,
"重新设置msg信息!");
String msg
= (String) m3.invoke(foo);
System.out.println(msg);
}
}

class Foo {
private String msg;

public Foo(String msg) {
this.msg = msg;
}

public void setMsg(String msg) {
this.msg = msg;
}

public String getMsg() {
return msg;
}

public void outInfo() {
System.out.println(
"这是测试Java反射的测试类");
}
}

 

 

控制台输出结果:

这是测试Java反射的测试类
重新设置msg信息!

Process finished with exit code
0

 

posted @ 2010-05-06 09:18  炎峰森林影  阅读(378)  评论(0编辑  收藏  举报