java反射机制,通过类名获取对象,通过方法名和参数调

来源:互联网 发布:python 字符串 decode 编辑:程序博客网 时间:2024/05/11 03:43

 try {
//得到类对象
Class c = Class.forName("完整类名");
Object yourObj = c.newInstance();
//得到方法
Method methlist[] = cls.getDeclaredMethods();
for (int i = 0; i < methlist.length; i++) {
Method m = methlist[i];
}
//获取到方法对象,假设方法的参数是一个int,method名为setAge
Method sAge = c.getMethod("setAge", new Class[] {int.class});
//获得参数Object
Object[] arguments = new Object[] { new Integer(37)};
//执行方法
sAge.invoke(yourObj , arguments);
} catch (Exception e) {
}

 

来自:http://blog.sina.com.cn/s/blog_65d46c880100iqh3.html

原创粉丝点击