java反射学习摘记

来源:互联网 发布:将软件添加到磁贴 编辑:程序博客网 时间:2024/05/21 18:40

JAVA中的反射机制 http://blog.csdn.net/liujiahan629629/article/details/18013523 (入门)

Java反射 http://www.importnew.com/17616.html (进阶)

Java API —— 反射 http://www.cnblogs.com/yangyquin/p/5230372.html 

通过Java反射调用方法 http://blog.csdn.net/ichsonx/article/details/9108173 (此篇较为简洁,推荐先看)


Class对象的获取

//第一种方式:  Classc1 = Class.forName("Employee");  //第二种方式:  //java中每个类型都有class 属性.  Classc2 = Employee.class;     //第三种方式:  //java语言中任何一个java对象都有getClass 方法  Employeee = new Employee();  Classc3 = e.getClass(); //c3是运行时类 (e的运行时类是Employee)  

在方法调用中,参数类型必须正确,这里需要注意的是不能使用包装类替换基本类型,比如不能使用Integer.class代替int.class。

//非静态方法调用Class cls = Class.forName("chb.test.reflect.Student");  Method setMethod = cls.getDeclaredMethod("setAge",int.class);  setMethod.invoke(cls.newInstance(), 15)//static方法调用时,不必得到对象示例Class cls = Class.forName("chb.test.reflect.Student");  Method staticMethod = cls.getDeclaredMethod("hi",int.class,String.class);  staticMethod.invoke(cls,20,"chb");//这里不需要newInstance  //staticMethod.invoke(cls.newInstance(),20,"chb");

如果直接通过反射给类的private成员变量赋值,是不允许的,但可以通过setAccessible方法解决

Class cls = Class.forName("chb.test.reflect.Student");  Object student = cls.newInstance();  Field field = cls.getDeclaredField("age");  field.setAccessible(true);//设置允许访问  field.set(student, 10);  System.out.println(field.get(student));



原创粉丝点击