BeanUtils 的使用 :资料戳这里
BeanUtils 中使用了 反射的原理。这里没有对其源码分析,回顾下反射的相关知识。
使用反射首先要先获得Class类,获取方式有以下三种:
第一种
HelloWorldImpl impl = new HelloWorldImpl();//这一new 产生一个Student对象,一个Class对象。 Class helloworld = impl.getClass();//获取Class对象
第二种
Class helloworld = HelloWorldImpl.class;
第三种
Class helloworld = Class.forName("helloWorld.HelloWorld");//注意此字符串必须是真实路径,就是带包名的类路径,包名.类名
通过反射获取构造方法
Constructor getConstructor(Class[] params) 根据构造函数的参数,返回一个具体的具有public属性的构造函数
Constructor getConstructors() 返回所有具有public属性的构造函数数组
Constructor getDeclaredConstructor(Class[] params) 根据构造函数的参数,返回一个具体的构造函数(不分public和非public属性)
Constructor getDeclaredConstructors() 返回该类中所有的构造函数数组(不分public和非public属性)
获取成员方法的方法
Method getMethod(String name, Class[] params) 根据方法名和参数,返回一个具体的具有public属性的方法 Method[] getMethods() 返回所有具有public属性的方法数组 Method getDeclaredMethod(String name, Class[] params) 根据方法名和参数,返回一个具体的方法(不分public和非public属性) Method[] getDeclaredMethods() 返回该类中的所有的方法数组(不分public和非public属性)
获取成员属性的方法
Field getField(String name) 根据变量名,返回一个具体的具有public属性的成员变量
Field[] getFields() 返回具有public属性的成员变量的数组
Field getDeclaredField(String name) 根据变量名,返回一个成员变量(不分public和非public属性)
Field[] getDelcaredField() 返回所有成员变量组成的数组(不分public和非public属性)
实例类
public class Students { public String name; private int age; String six; protected String height; public Students() { super(); } public Students(String name, int age, String six, String height) { super(); this.name = name; this.age = age; this.six = six; this.height = height; } Students(String name) { this.name = name; } protected Students(String name, int age) { this.name = name; this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getSix() { return six; } public void setSix(String six) { this.six = six; } public String getHeight() { return height; } public void setHeight(String height) { this.height = height; } }
以下是使用
Class clazz = Class.forName("mytest.Students");
//获取公有、无参的构造方法
Constructor con = clazz.getConstructor(null);
//调用构造方法
Object obj = con.newInstance();
当字段为 private 时要设置 通过 getDeclaredField 方法得到字段后要设置允许在反射时访问私有变量 setAccessible(true);
Field idField = obj.getDeclaredField( "age" ) ;
idField.setAccessible( true );
idField.set(obj , 10) ;
//获取 setName() 方法
Method setName = obj.getDeclaredMethod( "setName", String.class );
setName.setAccessible( true );
setName.invoke( obj, "jack" ) ;