相同属性的类相互转换
两个具有相同属性的pojo(对象)类相互转换。或父类向子类转换。
定义方法类MyBeanUtil 如下:
类MyBeanUtil 继承原有类BeanUtils
public class MyBeanUtil extends BeanUtils {
protected static Format format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
public static void populate(Object bean, Map properties)
throws IllegalAccessException, InvocationTargetException {
// Do nothing unless both arguments have been specified
if ((bean == null) || (properties == null)) {
return;
}
// Loop through the property name/value pairs to be set
Iterator names = properties.keySet().iterator();
while (names.hasNext()) {
String name = (String) names.next();
// Identify the property name and value(s) to be assigned
if (name == null) {
continue;
}
Object value = properties.get(name);
try {
Class clazz = PropertyUtils.getPropertyType(bean, name);
if (null == clazz) {
continue;
}
String className = clazz.getName();
if (className.equalsIgnoreCase("java.util.Date")) {
if (value == null || value.equals("")) {
continue;
} else if(value.toString().length()==10) {
setProperty(bean, name, (java.util.Date)format.parseObject((String) value+" 00:00:00"));
continue;
}else {
setProperty(bean, name, (java.util.Date)format.parseObject((String) value));
continue;
}
}
setProperty(bean, name, value);
} catch (Exception e) {
continue;
}
} }
}
使用方法:
MyBeanUtil.populate(stoVO,MyBeanUtil.describe(sto));
stoVO:子类对象
sto:父类对象
在页面显示时,如果需要显示视图值。可以再stoVO类中写。