Java通过反射调用对象的方法
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);
编辑推荐:
温馨提示:因考试政策、内容不断变化与调整,长理培训网站提供的以上信息仅供参考,如有异议,请考生以权威部门公布的内容为准! (责任编辑:长理培训)
点击加载更多评论>>