反射
反射:(程序运行时,动态加载类,获取类的信息,从而使用类及其对象的变量和方法)
将类的各个部分重新封装成一个Class类 对象,然后通过这个class类 对象操作其对应的类(获取、修改), 这就是反射机制。
带Declared可以获取包括public及public以外的所有,Field、Constructor、method
<--Field-->
Field[] getFields()
Field getField(String name) //只能获取public的
Field[] getDeclaredFields()
Field getDeclaredField(String name)//能获取所有
Field.setAccessible(true) //暴力反射
field1.get() //获取值
<--Method-->
Method[] getMethods()
Method getMethod(String name) //只能获取public的
Method[] getDeclaredMethods()
Method getDeclaredMethod(String name)//能获取所有
method.invoke();//执行方法
<--Constructor-->
Constructor[] getConstructors()
Constructor getConstructor(String name) //只能获取public的
Constructor[] getDeclaredConstructors()
Constructor getDeclaredConstructor(String name)//能获取所有
Constructor.newInstance();//执行,创建实例
Constructor.newInstance();
method.invoke();
暴力反射: Field.setAccessible(true)【能获取private 的值】
实际上setAccessible是启用和禁用访问安全检查的开关
举例:
public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException {
GoodsTest goods = new GoodsTest();
goods.setId("1");
Field id = goods.getClass().getDeclaredField("id");
Field goodsName = goods.getClass().getDeclaredField("goodsName");
goodsName.set(goods,"张飞");
//Field.setAccessible(true);
Object o = id.get(goods);
Field[] declaredFields = goods.getClass().getDeclaredFields();
Object o1 = declaredFields[0].get(goods);
String name = declaredFields[0].getName();
}