java学习

java学习

 

BeanUtils复制对象的日期转换

public class Bean1 {
private String a;
private String b;
private String time;
public String getA() {
return a;
}
public void setA(String a) {
this.a = a;
}
public String getB() {
return b;
}
public void setB(String b) {
this.b = b;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
}
public class Bean2 {
private int a;
private String b;
private Date time;
public int getA() {
return a;
}
public void setA(int a) {
this.a = a;
}
public String getB() {
return b;
}
public void setB(String b) {
this.b = b;
}
public Date getTime() {
return time;
}
public void setTime(Date time) {
this.time = time;
}
}
import java.lang.reflect.InvocationTargetException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.Converter;
public class Test {
public static void main(String[] args) throws IllegalAccessException, InvocationTargetException {
Bean1 bean1 = new Bean1();
bean1.setA("22");
bean1.setB("fff");
bean1.setTime("2017-01-22 11:11:11");
Bean2 bean2 = new Bean2();
resp();
BeanUtils.copyProperties(bean2, bean1);
System.out.println(bean2.getA());
System.out.println(bean2.getB());
System.out.println(bean2.getTime());
}
private static void resp() {
ConvertUtils.register(new Converter() {
@Override
public Object convert(Class arg0, Object value) {
if(value != null &&!"".equals(value.toString())){
String v=value.toString();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:MM:ss");
try {
return sdf.parse(v);
} catch (ParseException e) {
e.printStackTrace();
}
}
return null;
}
}, Date.class);
}
}

posted on 2017-08-16 16:31 杨军威 阅读(465) 评论(0)  编辑  收藏


只有注册用户登录后才能发表评论。


网站导航:
 

导航

统计

常用链接

留言簿

随笔档案

搜索

最新评论

阅读排行榜

评论排行榜