通过java反射调用方法
这是个测试用的例子,通过反射调用对象的方法。
testref.java
import java.lang.reflect.method;
import java.lang.reflect.invocationtargetexception;
/**
* created by intellij idea.
* file: testref.java
* user: leizhimin
* date: 2008-1-28 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