您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

通过Java反射调用方法

2024/3/18 11:32:12发布40次查看
通过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
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product