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中的更多相关文章

  1. Struts2把数据封装到集合中之封装到map中

    struts框架封装数据可以封装到集合中也可以封装到map中,该篇博客主要讲解将数据封装到map中. 1. 封装复杂类型的参数(集合类型 Collection .Map接口等) 2. 需求:页面中有可 ...

  2. ASP.NET MVC之表单集合数据自动绑定到对象属性(集合)中

    前言 之前没遇到过这个问题,在项目中遇到这个问题时想法挺好,按照流程走下去,结果事与愿违,于是开始探索着解决方案,接下来我们来看看这个问题,早已经明了的童鞋请绕道,此文仅供未遇到的童鞋提供一种解决方案 ...

  3. unreal3对象属性自动从配置文件中加载的机制

    unrealscript中有两个与属性自动配置相关的关键字: config/globalconfig 当把它们应用于属性时,对象在创建后,该属性的初始值会被自动设置为相对应ini文件中的值. 举例来说 ...

  4. 3. 如何封装查询条件与查询结果到map中

    public Map<String, Object> queryOrderStatus(String orderNo) { // 查询到的结果与查询的条件一一对应,封装到map中! Str ...

  5. Struts2把数据封装到集合中之封装到Collection中

    数据封装到集合中,可以封装到集合中,也可以封装到Map中.该篇博客主要讲解数据封装到集合中的封装到Collection中. 1. 封装复杂类型的参数(集合类型 Collection .Map接口等) ...

  6. ES6_入门(3)_顶层对象属性

    //顶层对象属性:在ES5中,顶层对象的属性与全局变量是等价的.以下代码中,为顶层对象的属性赋值与全局变量的赋值,是同一件事. window.a=10; console.log(window.a); ...

  7. JS 自定义对象 属性

    js自定义对象 一,概述 在Java语言中,我们可以定义自己的类,并根据这些类创建对象来使用,在Javascript中,我们也可以定义自己的类,例如定义User类.Hashtable类等等. 目前在J ...

  8. js自定义对象.属性 笔记

    <一> js自定义对象 一,概述 在Java语言中,我们可以定义自己的类,并根据这些类创建对象来使用,在Javascript中,我们也可以定义自己的类,例如定义User类.Hashtabl ...

  9. C++类继承中,基类/当前对象属性/当前对象的构造顺序

    [1]中提到,规范的派生类构造函数三个要点: 首先创建基类对象 应通过成员初始化列表,创建基类对象 应该初始化本派生类新增的成员变量 那在构造派生类实例的过程中,其基类(以及多继承的时候多个基类)/当 ...

随机推荐

  1. php调试小技巧

    /** * 用来调试输出结果 * @param type $data * @return type */ function shionyu_debug($data) { ob_start(); var ...

  2. 可以将一些配置信息已json格式存在数据库中读取的时候序列化。

    public partial class json序列化 : System.Web.UI.Page    {        protected void Page_Load(object sender ...

  3. js获取非行间样式/定义样式

    <!--DOCTYPE html--> <html> <head> <meta charset="utf-8" /> <sty ...

  4. oc-32-@property示例

    Goods.h #import <Foundation/Foundation.h> typedef struct{ int year; int month; int day; } MyDa ...

  5. gpus_ReturnGuiltyForHardwareRestart 错误

    经查出是glScissor长宽不能为0,在某些设备上会出问题

  6. android studio 预览保持,因为是SDK版本过高,可以点击小图标机器人修改SDK版本号。

    Exception raised during rendering: com/android/util/PropertiesMap

  7. IIS 之 HTTP 错误 404.3 - Not Found(由于扩展配置问题而无法提供您请求的页面...)

    错误如下图所示: 其实在IIS7中肯定能支持的的,只是我们在Win7中安装IIS7的时候没有勾选这些功能,具体方法如下: 1.依次打开" 控制面板→程序→程序和功能→打开或关闭Windwos ...

  8. java解析excel2003和excel2007:The supplied data appears to be in the office 2007+XML Polonly supports OLE2 office documents

    上传excel解析存到数据库时报: org.apache.poi.poifs.filesystem.OfficeXmlFileException: The supplied data appears ...

  9. solr 竞价排行

    在理想的情况下,搜索引擎只返回与用户查询相关的文档.而在现实的查询中,编辑(没发现更合适的表达)通常需要指定特定文档在搜索结果中的特定位置.这样做有很多原因.或许 “置顶” 的文档就是最好的查询结果. ...

  10. CALayer实现遮罩效果

    #import "ViewController.h" @interface ViewController () @property(nonatomic,strong)CALayer ...