java原生反射的使用
反射构造对象
//获得指定对象的构造方法,参数值传入与构造方法参数对应的类型
Constructor> constructors = peopleClass.getConstructor(String.class);
//分为无参和有参,参数传入与构造方法参数对应的值,获得对象引用
People people = (People) constructors.newInstance("Devin");
反射方法
函数
作用
备注
getDeclaredMethod
获取指定的 private、protected、default、public 的函数
只能取到的该类自身中定义的函数,从父类中继承的函数不能够获取到。
getDeclaredMethods
获取全部的 private、protected、default、public 的函数
只能取到的该类自身中定义的函数,从父类中继承的函数不能够获取到。
getMethod
获取指定的 public 函数
父类中的公有函数也能够获取到
getMethods
获取全部的 public 函数
父类中的公有函数也能够获取到
setAccessible()
设置该方法是否可被访问
设置true表示可以访问该方法
invoke()
调用该方法,第一个参数表示该方法所在类的对象,第二个参数传入该方法所需的参数值
如果该方法有返回值,则返回方法执行后的返回值,如果没有,则返回null
People people = new People("lisi");
Class extends People> aClass = people.getClass();
Method method = aClass.getDeclaredMethod("setAge", int.class);
//设置true表示可以访问该方法
method .setAccessible(true);
//调用此方法,如果方法有返回值,则返回方法执行后的返回值,如果没有,则返回 null
Object obj=method .invoke(people, 20);
反射字段
函数
作用
备注
getDeclaredField
获取指定的 private、protected、default、public 的字段
只能取到的该类自身中定义的字段,从父类中继承的字段不能够获取到。
getDeclaredFields
获取全部的 private、protected、default、public 的字段
只能取到的该类自身中定义的字段,从父类中继承的字段不能够获取到。
getField
获取指定的 public 字段
父类中的公有字段也能够获取到
getFields
获取全部的 public 字段
父类中的公有字段也能够获取到
setAccessible()
设置该字段是否可被访问
设置true表示可以访问该字段
set()/setInt()/...
修改字段的值
第一个参数为字段所在的类的对象,第二个参数为要修改的值 (final 字段是不可修改的)
get()/getInt()/...
获取字段的值
参数为属性所在的类的对象,表示获取该类的该属性,
People people = new People("lisi");
Class extends People> aClass = people.getClass();
Field field = aClass.getDeclaredField("name");
field .setAccessible(true);
String name = (String) field .get(people);
joor反射库的使用
String name = null;
Kale kale;
// 【创建类】
kale = Reflect.on(Kale.class).create().get(); // 无参数
kale = Reflect.on(Kale.class).create("kale class name").get();// 有参数
System.err.println("------------------> class name = " + kale.getClassName());
// 【调用方法】
Reflect.on(kale).call("setName","调用setName");// 多参数
System.err.println("调用方法:name = " + Reflect.on(kale).call("getName"));// 无参数
// 【得到变量】
name = Reflect.on(kale).field("name").get();// 复杂
name = Reflect.on(kale).get("name");// 简单
System.err.println("得到变量值: name = " + name);
// 【设置变量的值】
Reflect.on(kale).set("className", "hello");
System.err.println("设置变量的值: name = " + kale.getClassName());
System.err.println("设置变量的值: name = " + Reflect.on(kale).set("className", "hello2").get("className"));