public static void main(String[] args) {
BeanWrapper company = new BeanWrapperImpl( new Company());
// setting the company name..
company.setPropertyValue( "name", "Some Company Inc.");
// ... can also be done like this:
PropertyValue value = new PropertyValue( "name", "Some Company Inc.");
company.setPropertyValue(value);
// ok, let's create the director and tie it to the company:
BeanWrapper jim = new BeanWrapperImpl( new Employee());
jim.setPropertyValue( "name", "Jim Stravinsky");
jim.setPropertyValue( new PropertyValue( "salary", "20000"));
company.setPropertyValue( "managingDirector", jim.getWrappedInstance());
// retrieving the salary of the managingDirector through the company
Float salary = (Float) company.getPropertyValue("managingDirector.salary" );
System. out.println(String. format("salary : %s", salary));
}
public class Company {
private String name;
private Employee managingDirector;
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public Employee getManagingDirector() {
return this.managingDirector;
}
public void setManagingDirector(Employee managingDirector) {
this.managingDirector = managingDirector;
}
}
public class Employee {
private float salary;
private String name;
public float getSalary() {
return salary;
}
public void setSalary( float salary) {
this.salary = salary;
}
public String getName() {
return name;
}
public void setName(String name) {
this. name = name;
}
}
public abstract class PropertyAccessorFactory {
/**
* Obtain a BeanWrapper for the given target object,
* accessing properties in JavaBeans style.
* @param target the target object to wrap
* @return the property accessor
* @see BeanWrapperImpl
*/
public static BeanWrapper forBeanPropertyAccess(Object target) {
return new BeanWrapperImpl(target);
}
/**
* Obtain a PropertyAccessor for the given target object,
* accessing properties in direct field style.
* @param target the target object to wrap
* @return the property accessor
* @see DirectFieldAccessor
*/
public static ConfigurablePropertyAccessor forDirectFieldAccess(Object target) {
return new DirectFieldAccessor(target);
}
}
扫描二维码关注公众号,回复:
4208996 查看本文章