package beanUtils;
import java.util.HashMap;
import java.util.Map;
/**
* Created by Andrew on 2015/12/4.
*/
public class Employee {
String firstName;
String lastName;
Employee[] subordinate;
Map address;
public Employee(){
firstName = "Adnrew";
lastName = "Chen";
subordinate = new Employee[]{new Employee("Shirley","Liu"),new Employee("Alex","Wang")};
address = new HashMap<>();
address.put("home", new Address("Changsha YueLuShan"));
}
private Employee(String firstName,String lastName){
this.firstName = firstName;
this.lastName = lastName;
}
public Address getAddress(String type) {
return address.get(type);
}
public void setAddress(String type, Address address) {
this.address.put(type, address);
}
public Employee getSubordinate(int index) {
return subordinate[index];
}
public void setSubordinate(int index, Employee subordinate) {
this.subordinate[index] = subordinate;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}public String getLastName() {
return this.lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
@Override
public String toString() {
return firstName+" "+lastName;
}
}
package beanUtils;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.PropertyUtils;
import java.lang.reflect.InvocationTargetException;
/**
* Created by Andrew on 2015/12/4.
*/
public class BeanUtilsTest {
public static void main(String[] args) {
Employee employee = new Employee();
try {
System.out.println((String) PropertyUtils.getSimpleProperty(employee, "firstName"));
System.out.println((String)PropertyUtils.getSimpleProperty(employee, "lastName"));
System.out.println(PropertyUtils.getIndexedProperty(employee, "subordinate[0]"));
System.out.println(PropertyUtils.getMappedProperty(employee, "address(home)"));
System.out.println(PropertyUtils.getNestedProperty(employee, "address(home).city"));
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
}
}
对于Indexed属性,PropertyUtils.getIndexedProperty(employee, "subordinate[0]")或是PropertyUtils.getIndexedProperty(employee, "subordinate",0)来获得。
对于Mapped属性,PropertyUtils.getMappedProperty(employee, "address(home)")PropertyUtils.getMappedProperty(employee, "address","home")来获得。
String city = employee.getAddress("home").getCity();
String city = (String) PropertyUtils.getNestedProperty(employee, "address(home).city");