对象属性封装到map中
package org.scivf.common.map; import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.HashMap;
import java.util.Map; import org.springframework.beans.BeanUtils; public class MapUtils { /**
* 把指定的复杂对象属性,按照指定的内容,封装到新的map中
*
* @param source
* 目标对象
* @param ps
* 需要封装到map中的属性
* @return
*/
public static Map<String, Object> obj2map(Object source, String[] ps) {
Map<String, Object> map = new HashMap<>();
if (source == null)
return null;
if (ps == null || ps.length < 1) {
return null;
}
for (String p : ps) {
PropertyDescriptor sourcePd = BeanUtils.getPropertyDescriptor(source.getClass(), p);
if (sourcePd != null && sourcePd.getReadMethod() != null) {
try {
Method readMethod = sourcePd.getReadMethod();
if (!Modifier.isPublic(readMethod.getDeclaringClass().getModifiers())) {
readMethod.setAccessible(true);
}
Object value = readMethod.invoke(source, new Object[0]);
map.put(p, value);
} catch (Exception ex) {
throw new RuntimeException("Could not copy properties from source to target", ex);
}
}
}
return map;
} public static <T> T map2Bean(Class<T> clazz, Map<String, Object> map) { T newInstance = null;
try {
newInstance = clazz.newInstance();
Field[] fields = clazz.getDeclaredFields();
for (Map.Entry<String, Object> entry : map.entrySet()) {
Object value = entry.getValue();
String key = entry.getKey();
for (Field field : fields) {
String fieldName = field.getName();
Class<?> fieldType = field.getType();
if (fieldName.toLowerCase().equals(key.toLowerCase())) {
value = processColumn(value, fieldType);
callSetter(newInstance, fieldName, fieldType, value);
break;
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return newInstance;
} protected static Object processColumn(Object value, Class<?> propType) throws SQLException { if (!propType.isPrimitive() && isNull(value)) {
return null;
} if (propType.equals(String.class)) {
return String.valueOf(value); } else if (propType.equals(Integer.TYPE) || propType.equals(Integer.class)) {
return (Integer) value; } else if (propType.equals(Boolean.TYPE) || propType.equals(Boolean.class)) {
return (Boolean) value; } else if (propType.equals(Long.TYPE) || propType.equals(Long.class)) {
return (Long) value; } else if (propType.equals(Double.TYPE) || propType.equals(Double.class)) {
return Double.valueOf(value.toString()); } else if (propType.equals(Float.TYPE) || propType.equals(Float.class)) {
return Float.valueOf(value.toString()); } else if (propType.equals(Short.TYPE) || propType.equals(Short.class)) {
return Short.valueOf(value.toString()); } else if (propType.equals(Byte.TYPE) || propType.equals(Byte.class)) {
return Byte.valueOf(value.toString()); } else if (propType.equals(Timestamp.class)) {
return new java.sql.Timestamp(((java.util.Date) value).getTime()); } else {
return value;
}
} private static boolean isNull(Object obj) { return (obj == null || "null".equals(obj.toString().trim()) || "".equals(obj.toString().trim())); } private static void callSetter(Object target, String fieldName, Class<?> fieldType, Object value)
throws SQLException, NoSuchMethodException, SecurityException { String setMethod = "set" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1); Method setter = target.getClass().getMethod(setMethod, fieldType); if (setter == null) {
return;
} Class<?>[] params = setter.getParameterTypes();
try {
// convert types for some popular ones
if (value instanceof java.util.Date) {
final String targetType = params[0].getName();
if ("java.sql.Date".equals(targetType)) {
value = new java.sql.Date(((java.util.Date) value).getTime());
} else if ("java.sql.Time".equals(targetType)) {
value = new java.sql.Time(((java.util.Date) value).getTime());
} else if ("java.sql.Timestamp".equals(targetType)) {
value = new java.sql.Timestamp(((java.util.Date) value).getTime());
}
} // Don't call setter if the value object isn't the right type
if (isCompatibleType(value, params[0])) {
setter.invoke(target, new Object[] { value });
} else {
throw new SQLException("Cannot set " + fieldName + ": incompatible types, cannot convert "
+ value.getClass().getName() + " to " + params[0].getName());
// value cannot be null here because isCompatibleType allows null
} } catch (IllegalArgumentException e) {
throw new SQLException("Cannot set " + fieldName + ": " + e.getMessage()); } catch (IllegalAccessException e) {
throw new SQLException("Cannot set " + fieldName + ": " + e.getMessage()); } catch (InvocationTargetException e) {
throw new SQLException("Cannot set " + fieldName + ": " + e.getMessage());
}
} private static boolean isCompatibleType(Object value, Class<?> type) {
// Do object check first, then primitives
if (value == null || type.isInstance(value)) {
return true;
} else if (type.equals(Integer.TYPE) && Integer.class.isInstance(value)) {
return true; } else if (type.equals(Long.TYPE) && Long.class.isInstance(value)) {
return true; } else if (type.equals(Double.TYPE) && Double.class.isInstance(value)) {
return true; } else if (type.equals(Float.TYPE) && Float.class.isInstance(value)) {
return true; } else if (type.equals(Short.TYPE) && Short.class.isInstance(value)) {
return true; } else if (type.equals(Byte.TYPE) && Byte.class.isInstance(value)) {
return true; } else if (type.equals(Character.TYPE) && Character.class.isInstance(value)) {
return true; } else if (type.equals(Boolean.TYPE) && Boolean.class.isInstance(value)) {
return true; }
return false; } }
对象属性封装到map中的更多相关文章
- Struts2把数据封装到集合中之封装到map中
struts框架封装数据可以封装到集合中也可以封装到map中,该篇博客主要讲解将数据封装到map中. 1. 封装复杂类型的参数(集合类型 Collection .Map接口等) 2. 需求:页面中有可 ...
- ASP.NET MVC之表单集合数据自动绑定到对象属性(集合)中
前言 之前没遇到过这个问题,在项目中遇到这个问题时想法挺好,按照流程走下去,结果事与愿违,于是开始探索着解决方案,接下来我们来看看这个问题,早已经明了的童鞋请绕道,此文仅供未遇到的童鞋提供一种解决方案 ...
- unreal3对象属性自动从配置文件中加载的机制
unrealscript中有两个与属性自动配置相关的关键字: config/globalconfig 当把它们应用于属性时,对象在创建后,该属性的初始值会被自动设置为相对应ini文件中的值. 举例来说 ...
- 3. 如何封装查询条件与查询结果到map中
public Map<String, Object> queryOrderStatus(String orderNo) { // 查询到的结果与查询的条件一一对应,封装到map中! Str ...
- Struts2把数据封装到集合中之封装到Collection中
数据封装到集合中,可以封装到集合中,也可以封装到Map中.该篇博客主要讲解数据封装到集合中的封装到Collection中. 1. 封装复杂类型的参数(集合类型 Collection .Map接口等) ...
- ES6_入门(3)_顶层对象属性
//顶层对象属性:在ES5中,顶层对象的属性与全局变量是等价的.以下代码中,为顶层对象的属性赋值与全局变量的赋值,是同一件事. window.a=10; console.log(window.a); ...
- JS 自定义对象 属性
js自定义对象 一,概述 在Java语言中,我们可以定义自己的类,并根据这些类创建对象来使用,在Javascript中,我们也可以定义自己的类,例如定义User类.Hashtable类等等. 目前在J ...
- js自定义对象.属性 笔记
<一> js自定义对象 一,概述 在Java语言中,我们可以定义自己的类,并根据这些类创建对象来使用,在Javascript中,我们也可以定义自己的类,例如定义User类.Hashtabl ...
- C++类继承中,基类/当前对象属性/当前对象的构造顺序
[1]中提到,规范的派生类构造函数三个要点: 首先创建基类对象 应通过成员初始化列表,创建基类对象 应该初始化本派生类新增的成员变量 那在构造派生类实例的过程中,其基类(以及多继承的时候多个基类)/当 ...
随机推荐
- iOS开发——使用技术OC篇&简单九宫格锁屏功能的实现与封装
简单九宫格锁屏功能的实现与封装 首先来看看最后的实现界面. 在这开始看下面的内容之前希望你能先大概思考活着回顾一下如果 你会怎么做,只要知道大概的思路就可以. 由于iphone5指纹解锁的实现是的这个 ...
- Cocos2d-x内存管理研究<二>
http://hi.baidu.com/tzkt623/item/46a26805adf7e938a3332a04 上一篇我们讲了内核是如何将指针加入管理类进行管理.这次我将分析一下内核是如何自动 ...
- 错误“Unexpected namespace prefix "xmlns" found for tag LinearLayout”的解决方法
编写布局代码时发现xml脚本出现错误“Unexpected namespace prefix "xmlns" found for tag LinearLayout”,原来是一个na ...
- Long Long Message 后缀数组入门题
Long Long Message Time Limit: 4000MS Memory Limit: 131072K Total Submissions: 22564 Accepted: 92 ...
- solr 范围查询
[]表示查询一个包括边界范围, {}表示查询一个不包括边界范围 A TO * 表示没有上界即>=A或是>A ,视使用的是[]还是{}而定 * TO A 表示没有下界即<=A或是< ...
- 10. Android框架和工具之 AppMsg(消息提示)
1. AppMsg 优雅的弹出类似Toast的消息提示,支持3种状态Alert(警告),Confirm(确认)以及Info(消息). 2. AppMsg使用: (1)AppMsg下载地址 ...
- JavaScript工厂模式代码
function createPerson(name,age,job){ var o=new Object(); o.name=name; o.age=age; o.job=job; o.sayNam ...
- Hosts文件是什么?
Hosts文件主要作用是定义IP地址和主机名的映射关系,是一个映射IP地址和主机名的规定.可以用文本文件打开!当用户在浏览器中输入一个需要登录的 网址时,系统会首先自动从Hosts文件中寻找对应的IP ...
- 如何将你自己的Python package发布到PyPI上
零.前言 最近做了一个小工具,查询IP或者域名的归属地.做完之后想发布到PyPI上,这样大家就可以通过pip来安装了. 在发布的过程中遇到了一些问题,也学到了很多东西.记录到这篇文章中.希望对大家有所 ...
- 转: ImageMagick 命令行的图片处理工具(客户端与服务器均可用)
http://www.imagemagick.com.cn/ 关于ImageMagick ImageMagick (TM) 是一个免费的创建.编辑.合成图片的软件.它可以读取.转换.写入多种格式的图片 ...