2.3反射
反射是一种在程序运行时,动态的获取一个类的所有属性和方法(也能获取到private权限的属性及方法),并能利用得到的类构建对象。
Class对象是存储获得类信息的载体
如何获得Class对象?三种方法
public class Demo2 {
int i;
public static void main(String[] args) throws ClassNotFoundException {
Class c1 = Demo2.class;
Class c2 = new Demo2().getClass();
Class c3 = Class.forName("Demo2");
}
}
如何获得类中属性,方法?
Constructor[] c = c1.getConstructors();//获取所有构造方法
Field[] f = c1.getDeclaredFields();//获取所有属性
Method[] m = c1.getDeclaredMethods();//获取所有方法
指定参数获得
Constructor<String > constructor = c1.getConstructor();
方法及属性的方法调用以此类推。
注:
getFields()与getDeclaredFields()区别:
getFields()只能访问类中声明为公有的字段,私有的字段它无法访问,能访问从其它类继承来的公有方法.
getDeclaredFields()能访问类中所有的字段,与public,private,protect无关,不能访问从其它类继承来的方法
getMethods()与getDeclaredMethods()区别:
getMethods()只能访问类中声明为公有的方法,能访问从其它类继承来的公有方法.
getDeclaredFields()能访问类中所有的字段,与public,private,protect无关,不能访问从其它类继承来的方法
getConstructors()与getDeclaredConstructors()区别:
getConstructors()只能访问类中声明为public的构造函数.
getDeclaredConstructors()能访问类中所有的构造函数,与public,private,protect无关
要是修改或者访问对象内的值时,private修饰的属性需要在修改或者访问前调用setAccessible(true)方法
获对象里的取值
Demo2 demo2 = new Demo2();
Class c1 = demo2.getClass();
Field f1 = c1.getDeclaredField("i");
f1.setAccessible(true);
System.out.println(f1.getInt(demo2));
修改对象里的值
Demo2 demo2 = new Demo2();
Class c1 = demo2.getClass();
Field f1 = c1.getDeclaredField("i");
f1.setAccessible(true);
f1.set(demo2,3);
System.out.println(f1.getInt(demo2));