本帖最后由 崔利鹏 于 2012-11-24 21:22 编辑
总是提示:Exception in thread "main" java.lang.NoSuchMethodException: com.itheima.Foo.getMsg()
at java.lang.Class.getDeclaredMethod(Class.java:1937)
at com.itheima.Test.main(Test.java:22)
public class Test {
public static void main(String[] args) throws SecurityException, NoSuchMethodException, IllegalArgumentException, 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 void outInfo() {
System.out.println("这是测试Java反射的测试类");
}
}
|