您的位置:首页 > 编程语言 > Java开发

利用java反射将map值封装到对象中

2016-07-28 14:56 956 查看
有时候我们需要将map里面的值依据键依次封装到对象里面。

这时需要简单的用下反射。

例子如下:

public void newLoadFromMap(Map<?,?> map) throws IllegalArgumentException, IllegalAccessException{
try {
Field[] fields = this.getClass().getDeclaredFields();//拿到对象所有的属性
for(Field f: fields){//遍历属性并赋值,赋值前要先判断属性类型
if (f.getGenericType().toString().equals(
"class java.lang.String")) { // 如果type是类类型,则前面包含"class ",后面跟类名
Object DBValue = null;
DBValue = map.getOrDefault(f.getName(), null);//getOrdefault->jdk8新特性,map中如果包含这个键,取其值,如果不包含,取第二个参数(默认值)
if (DBValue == null)
f.set(this, "");
else
f.set(this,DBValue.toString());
}
// 如果类型是Integer
if (f.getGenericType().toString().equals(
"class java.lang.Integer")) {
Object DBValue = null;
DBValue = map.getOrDefault(f.getName(), null);
if (DBValue == null)
f.set(this, null);
else
f.set(this,Integer.parseInt(DBValue.toString()));
}
// 如果类型是Date
if (f.getGenericType().toString().equals(
"class java.sql.Timestamp")) {
Object DBValue = null;
DBValue = map.getOrDefault(f.getName(), null);
if (DBValue == null)
f.set(this, null);
else{
SimpleDateFormat s = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
f.set(this,DateFormat.dateToTimestamp(s.parse(DBValue.toString()), "yyyy-MM-dd HH:mm:ss"));
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: