public class NodeDO {
private String name;
private String email;
private Date dateTime;
public String toString() {
return name + "\t" + email + "\t" + getDateTimeString();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Date getDateTime() {
return dateTime;
}
public String getDateTimeString() {
return NodeDOEditor.DEFAULT_DATE_FORMAT.format(dateTime);
}
public void setDateTime(Date dateTime) {
this.dateTime = dateTime;
}
基本类
public class TestDO {
private String nodeName;
private NodeDO nodeDO;
public String getNodeName() {
return nodeName;
}
public void setNodeName(String nodeName) {
this.nodeName = nodeName;
}
public NodeDO getNodeDO() {
return nodeDO;
}
public void setNodeDO(NodeDO nodeDO) {
this.nodeDO = nodeDO;
}
上述类中的属性包含另外一个类的引用
public class NodeDOEditor extends PropertyEditorSupport {
public final static SimpleDateFormat DEFAULT_DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
@Override
public void setAsText(String text) throws IllegalArgumentException {
String []tokens = text.split("\\|");
NodeDO nodeDO = new NodeDO();
nodeDO.setName(tokens[0]);
nodeDO.setEmail(tokens[1]);
try {
nodeDO.setDateTime(DEFAULT_DATE_FORMAT.parse(tokens[2]));
} catch (ParseException e) {
throw new IllegalArgumentException(e);
}
setValue(nodeDO);
}
设置转化参数
public class PropertiesEditorSample {
private final static Field[] TEST_FILEDS = TestDO.class.getDeclaredFields();
public static void main(String []args)
throws IllegalAccessException, IllegalArgumentException,
InvocationTargetException, IntrospectionException {
Map parameter = new HashMap() {
{
put("nodeName" , "tdd");
put("nodeDO" , "tdd|****@qq.com| 2014-11-24 21:54:00");
}
}; //模拟参数信息,就像requeset的ParameterMap类似
TestDO testDO = convertParameterToDO(parameter);
System.out.println(testDO.getNodeName());
System.out.println(testDO.getNodeDO());
}
private static TestDO convertParameterToDO(Map parameter)
throws IntrospectionException, IllegalAccessException,
IllegalArgumentException, InvocationTargetException {
TestDO testDO = new TestDO();
for(Field field : TEST_FILEDS) {
PropertyDescriptor propertyDescriptor = new PropertyDescriptor(field.getName() , TestDO.class);
Method method = propertyDescriptor.getWriteMethod();
if(field.getType() == String.class) {
method.invoke(testDO, parameter.get(field.getName()));
}else {
PropertyEditor propertyEditor = PropertyEditorManager.findEditor(field.getType());//查找Editor
if(propertyEditor != null) {
propertyEditor.setAsText(parameter.get(field.getName()));
method.invoke(testDO, propertyEditor.getValue());
}else {
System.out.println("properties : " + field.getName() + " , can not find editor");
}
}
}
return testDO;
}
这个是本次代码的核心。
运行结果:
tdd
tdd ****@qq.com 2014-11-24 21:54:00