public class Foo {
private String str;
public String getStr() {
return str;
}
public void setStr(String str) {
this.str = str;
}
public Foo(String str) {
this.str=str;
}
public void showInfo(){
System.out.println("这是测试Java反射的测试类!");
}
}
package Sousou;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class FooTest {
public static void main(String[] args) throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
Foo foo=new Foo("这是一个Foo对象!");
Class class1=foo.getClass();
Method m1=class1.getDeclaredMethod("showInfo");
Method m2=class1.getDeclaredMethod("setStr", String.class);
Method m3=class1.getDeclaredMethod("getStr");
m1.invoke(foo);
m2.invoke(foo, "重新设置str信息!");
String str=(String) m3.invoke(foo);
System.out.println(str);
}
}
输出结果:这是测试Java反射的测试类!
重新设置str信息!