对象属性封装到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]中提到,规范的派生类构造函数三个要点: 首先创建基类对象 应通过成员初始化列表,创建基类对象 应该初始化本派生类新增的成员变量 那在构造派生类实例的过程中,其基类(以及多继承的时候多个基类)/当 ...
随机推荐
- android 自定义ViewGroup和对view进行切图动画实现滑动菜单SlidingMenu
示意图就不展示了,和上一节的一样,滑动菜单SlidingMenu效果如何大家都比较熟悉,在这里我简单说明一下用自定义ViewGroup来实现. 实现方法:我们自定义一个ViewGroup实现左右滑动, ...
- android自定义TabWidget样式
先看看效果图吧,个人觉得图标丑了点,不过还行,自己用PS做的 下面是全部代码和流程,一定要按流程顺序来,不然错误! 1.tabhost.xml <TabHost xmlns:android=&q ...
- Xcode常见的编译、运行等错误的解决
Xcode常见的编译.运行等错误的解决 项目没找到Info.plist的错误 The solution for this particular instance of the error was “I ...
- docker + swarm 集群
docker + swarm 集群 导读 Swarm是Docker公司在2014年12月初新发布的容器管理工具.和Swarm一起发布的Docker管理工具还有Machine以及Compose.Swar ...
- Makefile中指示符“include”、“-include”和“sinclude”的区别
转:http://www.cnblogs.com/xmphoenix/archive/2012/02/22/2363335.html 指示符“include”.“-include”和“sinclude ...
- solr默认查询设置
在搜索过程中,如果我们每次请求中都传入很多固定的参数,会很繁琐,这里再solrconfig.xml中初始化定义一些不经常改动的搜索参数: <requestHandler name="/ ...
- cocos2dx3.0-执行cocos compile -p win32 命令出现错误 MSB8020 以及编译出来的exe 无法打开的问题
本文由@呆代待殆原创,转载请注明出处:http://www.cnblogs.com/coffeeSS/ 当博主准备把cocos工程用cocos命令行编译出来的时候,报出了MSB8020的错误,具体如下 ...
- ios----protocol, optional ,delegate
ios----protocol,delegate protocol——协议 协议是用来定义对象的属性,行为和用于回调的. 协议中有两个关键字@private和@optional,@privat ...
- 菜菜菜鸟学习之JavaWeb 入门1(自己的学习理解,不对之处请大神们多多指教啊)
一.相关基础知识 1.C/S(Client/Server)架构和B/S(Browser/Server)架构 首先说C/S架构,简单讲其实很常见,类似QQ等需要下载客户端的应用程序就是建立在C/S架构中 ...
- Oracl用代码建标
建标还可以通过编写代码的方式实现,这样在建许多类似的表的时候可以极高建表的效率. create table SCORE --建立表名( ...