对象属性封装到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开发——动画编程Swift篇&(三)CATransition动画
CATransition动画 // MARK: - CATransition动画 // /* 动画样式 */ // let kCATransitionFade: NSString! //翻页 // l ...
- Unity3d截图保存到Android相册的实现
Unity3d截图保存到Android相册的实现-----------------------------ultrasoon 季风原创--------------------------------- ...
- qt的安装和debug
qt-opensource-windows-x86-msvc2013_64_opengl-5.3.0 这个已经包含了qt-creator-opensource-windows-x ...
- epoll的使用
http://blog.csdn.net/ljx0305/article/details/4065058 epoll - I/O event notification facility 在linu ...
- iOS 左右滑动 手势 响应方法
1. @property (nonatomic, strong) UISwipeGestureRecognizer *leftSwipeGestureRecognizer; @property (no ...
- 使用SourceTree
SourceTree是个git的GUI软件. 教程将“使用Git”那个小节可视化,更为直观. 第一次启动的时候选择忽略,然后直接进入界面. 填入git地址与注册邮箱即可 例如mindset这本书的g ...
- Js 实现五级联动
js实现多级联动的方法很多,这里给出⼀种5级联动的例子,其实可以扩展成N级联动,在做项目的时候碰到了这样⼀个问题但是有不能从数据库中动态的加载这些选项,所以只有想办法从单个的页面着手来处理了,应为项目 ...
- xe5 android tts(Text To Speech)
xe5 android tts(Text To Speech) TTS是Text To Speech的缩写,即“从文本到语音”,是人机对话的一部分,让机器能够说话. 以下代码实现xe5 开发的文本转 ...
- Unhandled Error in Silverlight Application “Syncfusion.Silverlight.Olap.Gauge.OlapGauge”的类型初始值设定项引发异常
Silverlight 在运行时,如果出现如下错误: 检查生成的xap文件,解压出来,看是否里面包含该DLL:Syncfusion.Silverlight.Olap.Gauge.OlapGauge
- hdu-5686 Problem B(斐波那契数列)
题目链接: Problem B Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others) ...