Vulcan 的回答是正确的,但另一种选择是使用Apache 的 BeanUtils。例如,给定类:
public class Employee {
public Address getAddress(String type);
public void setAddress(String type, Address address);
public Employee getSubordinate(int index);
public void setSubordinate(int index, Employee subordinate);
public String getFirstName();
public void setFirstName(String firstName);
public String getLastName();
public void setLastName(String lastName);
}
你可以做:
Employee employee = ...;
String firstName = (String) PropertyUtils.getSimpleProperty(employee, "firstName");
String lastName = (String) PropertyUtils.getSimpleProperty(employee, "lastName");
... manipulate the values ...
PropertyUtils.setSimpleProperty(employee, "firstName", firstName);
PropertyUtils.setSimpleProperty(employee, "lastName", lastName);
或者:
DynaBean wrapper = new WrapDynaBean(employee);
String firstName = wrapper.get("firstName");
还有很多其他访问 bean 的方法,比如Map
为值创建一个属性。有关更多示例,请参阅用户指南。