spring 里用beanwrapper的类可动态对一个类的属性getter,setter调用

package test;

import org.springframework.beans.BeanWrapper;
import org.springframework.beans.PropertyAccessorFactory;
import test.model.Person;
import test.model.Student;

public class Test {

public static void main(String[] args) {
Person p = new Person();
p.setId(10000);
p.setName("张三");
//p.setStudent(new Student());
BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(p);
bw.setPropertyValue("name", "五四");
//如果嵌套对象为null,则会自动创建一个对象出来(注意嵌套对象一定要有一个无参的构造方法)
bw.setAutoGrowNestedPaths(true);
bw.setPropertyValue("student.address", "香港中文大学");
//System.out.println(p.getName());
//System.out.println(p.getStudent().getAddress());
System.out.println(bw.getPropertyValue("name"));
System.out.println(bw.getPropertyValue("student.address"));

//输出结果:   五四
               香港中文大学

}
}





package test.model;

public class Person {
private String name;

private int id;

private Student student;

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public int getId() {
return id;
}

public void setId(int id) {
this.id = id;
}

public Student getStudent() {
return student;
}

public void setStudent(Student student) {
this.student = student;
}


}


package test.model;

public class Student {

public final static String school = "中国传媒大学";

private String className = "软件工程2班";

private String address;

public String getAddress() {
return address;
}

public void setAddress(String address) {
this.address = address;
}

private void test(){
System.out.println("执行了test=========================== ");
}

}


备注:

DirectFieldAccessor
Spring内部大量使用BeanWrapper进行属性取值赋值(setter/getter),不过到目前为止没有简单的办法去获取对象字段值;之前都是通过ReflectionUtils获取Field然后进行操作;Spring 4.1提供了DirectFieldAccessor来完成此功能:

        //嵌套设置/访问对象字段数据
        DirectFieldAccessor accessor = new DirectFieldAccessor(bean);
        //如果嵌套对象为null,字段创建
        accessor.setAutoGrowNestedPaths(true);
        //设置字段值
        accessor.setPropertyValue("bean2.name", "zhangsan");
        //读取字段值
        System.out.println(accessor.getPropertyValue("bean2.name"));




猜你喜欢

转载自qi20088.iteye.com/blog/2231358