首页 > 其他 > 详细

反射机制

时间:2014-01-26 19:23:20      阅读:406      评论:0      收藏:0      [点我收藏+]

public class Test {

public static void main(String[] args) throws NoSuchMethodException, Exception {
/**
* 根据构造函数创建对象
*/
Class s[]=new Class[]{String.class,Integer.class};
Constructor<Person> cons=Person.class.getConstructor(s);
Person p=cons.newInstance("bai",10);
System.out.println(p.getName());
/**
* 根据类本身创建默认构造函数的对象
*/
//Person p1=Person.class.newInstance();
Student stu=Student.class.newInstance();
/**
* 调用方法
*/

Method m=Person.class.getMethod("setName", String.class);
m.invoke(p, "nihao");
m=Person.class.getMethod("getName");
System.out.println(m.invoke(p));
/**
* 属性操作
* 更换私有属性的值
*/

Field[] f=Person.class.getDeclaredFields();
f[0].setAccessible(true);
f[0].set(p,"wohao");
System.out.println(m.invoke(p));



}

}

反射机制

原文:http://www.cnblogs.com/Wen-yu-jing/p/3534219.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!