java中两个对象间的属性值复制,比较,转为map方法实现
package com.franson.study.util; import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map; import org.apache.avalon.framework.service.ServiceException;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; public class BeanUtil { private static Log log = LogFactory.getLog(BeanUtil.class); /**
* 两对象之间的拷贝(在目标对象中存在的所有set方法,如果在源对象中存在对应的get方法,不管源对象的get方法的返回值是否为null,都进行拷贝)
* 仅拷贝方法名及方法返回类型完全一样的属性值
* @param desc 目标对象
* @param orig 源对象
* @param excludeFields 不拷贝的field(多个用逗号隔开)
*/
public static void copyPropertiesNotForce(Object desc, Object orig,String excludeFields) {
copyPropertiesNotForce(desc, orig, excludeFields, true);
}
/**
* 两对象之间的拷贝(在目标对象中存在的所有set方法,如果在源对象中存在对应的get方法,不管源对象的get方法的返回值是否为null,都进行拷贝)
* 仅拷贝方法名及方法返回类型完全一样的属性值
* @param desc 目标对象
* @param orig 源对象
* @param excludeFields 源对象
* @param isCopyNull 为null的属性是否拷贝(true拷贝null属性;false不拷贝null属性)
* @param excludeFields 不拷贝的field(多个用逗号隔开)
*/
public static void copyPropertiesNotForce(Object desc, Object orig,String excludeFields, boolean isCopyNull) {
Class<?> origClass = orig.getClass();
Class<?> descClass = desc.getClass(); Method[] descMethods = descClass.getMethods();
Method[] origMethods = origClass.getMethods(); boolean needExclude = false; //是否需要过滤部分字段
if(!StringUtil.isEmpty(excludeFields)){
needExclude = true;
excludeFields = "," + excludeFields.toLowerCase() + ",";
} Map<String,Method> methodMap = new HashMap<String,Method>();
for (int i = 0; i < origMethods.length; i++) {
Method method = origMethods[i];
String methodName = method.getName();
if (!methodName.equals("getClass")
&& methodName.startsWith("get")
&& (method.getParameterTypes() == null || method
.getParameterTypes().length == 0)) {
if(needExclude && excludeFields.indexOf(methodName.substring(3).toLowerCase()) > -1){
continue;
}
methodMap.put(methodName, method);
}
}
for (int i = 0; i < descMethods.length; i++) {
Method method = descMethods[i];
String methodName = method.getName();
if (!methodName.equals("getClass")
&& methodName.startsWith("get")
&& (method.getParameterTypes() == null || method
.getParameterTypes().length == 0)) {
if (methodMap.containsKey(methodName)) {
Method origMethod = (Method) methodMap.get(methodName);
try {
if (method.getReturnType().equals(
origMethod.getReturnType())) {
Object returnObj = origMethod.invoke(orig, null);
if(!isCopyNull && returnObj == null){
continue;
} String field = methodName.substring(3);
String setMethodName = "set" + field;
Method setMethod = descClass.getMethod(
setMethodName, new Class[] { method
.getReturnType() });
setMethod.invoke(desc, new Object[] { returnObj });
}
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
}
}
}
} /**
* 两对象之间的拷贝(在目标对象中存在的所有set方法,如果在源对象中存在对应的get方法,不管源对象的get方法的返回值是否为null,都进行拷贝)
* 仅拷贝方法名及方法返回类型完全一样的属性值
* @param desc 目标对象
* @param orig 源对象
*/
public static void copyPropertiesNotForce(Object desc, Object orig) {
copyPropertiesNotForce(desc, orig, null);
} /**
* 两对象之间的拷贝(在目标对象中存在的所有set方法,如果在源对象中存在对应的get方法,源对象的get方法的返回值为null的不拷贝)
* 仅拷贝方法名及方法返回类型完全一样的属性值
* @param desc 目标对象
* @param orig 源对象
* @param excludeFields 不拷贝的field(多个用逗号隔开)
*/
public static void copyPropertiesNotNull(Object desc, Object orig) {
copyPropertiesNotForce(desc, orig, null, false);
} public static void copyPropertiesNotNull(Object desc, Object orig,String excludeFields) {
copyPropertiesNotForce(desc, orig, excludeFields, false);
}
/**
* 判断两个对象的所有相同属性值是否相等,注意尽是比较相同的属性,对于A对象属性比B对象属性多,如果相同属性值相同,则返回为true
* @param desc
* @param orig
* @return 相等返回true,否则返回false
* @throws CrmBaseException
*/
public static boolean isEqualBeanProperties(Object desc, Object orig) throws CrmBaseException {
String result= compareBeanProperties(desc,orig);
if(result.equals("[]"))
return true;
return false;
}
/**
* 比较两个Bean相同字段的值(以源对象的值为基准,json串中显示目标对象中的值)【仅比较可转换为string的类型】
* @param desc 目标对象
* @param orig 源对象
* @return String 不一致的字段json串
* @throws ServiceException
*/
public static String compareBeanProperties(Object desc, Object orig)
throws CrmBaseException {
Map<String, Object> map = new HashMap<String, Object>();
Class<?> origClass = orig.getClass();
Class<?> descClass = desc.getClass(); Method[] descMethods = descClass.getMethods();
Method[] origMethods = origClass.getMethods(); Map<String,Method> methodMap = new HashMap<String,Method>();
StringBuffer sb = new StringBuffer();
for (int i = 0; i < origMethods.length; i++) {
Method method = origMethods[i];
String methodName = method.getName();
if (!methodName.equals("getClass")
&& methodName.startsWith("get")
&& (method.getParameterTypes() == null || method
.getParameterTypes().length == 0)) {
methodMap.put(methodName, method);
}
}
for (int i = 0; i < descMethods.length; i++) {
Method method = descMethods[i];
String methodName = method.getName();
if (!methodName.equals("getClass")
&& methodName.startsWith("get")
&& (method.getParameterTypes() == null || method
.getParameterTypes().length == 0)) {
if (methodMap.containsKey(methodName)) {
Method origMethod = (Method) methodMap.get(methodName);
try {
if (method.getReturnType().equals(
origMethod.getReturnType())) {
Object origObj = origMethod.invoke(orig, null);
origObj = origObj == null ? "" : origObj; Method descMethod = descClass.getMethod(methodName,
null);
Object descObj = descMethod.invoke(desc, null);
descObj = descObj == null ? "" : descObj; if (!origObj.equals(descObj)) {
map.put(methodName.substring(3), descObj);
sb.append(",{'field':'");
sb.append(methodName.substring(3));
sb.append("','msg':'");
sb.append(descObj.toString().replaceAll("\'",
""));
sb.append("'}");
}
}
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
}
}
}
String str = "[";
if (sb.length() > 0) {
str += sb.substring(1);
}
return str + "]";
} /**
* bean转Map
* @param bean
* @return
*/
public static Map beanToMap(Object bean){
//return bean2Map(bean);
return objectToMap(bean);
} /**
* 通过字段名获取方法数组
* @param beanClass Class<?>
* @param fieldNameArray 要输出的所有字段名数组
* @return Method[]
*/
public static Method[] getMethods(Class<?> beanClass,String[] fieldNameArray){
Method[] methodArray = new Method[fieldNameArray.length]; String methodName;
String fieldName;
for (int i=0;i<fieldNameArray.length;i++) {
Method method = null;
fieldName = fieldNameArray[i];
methodName = fieldName.substring(0,1).toUpperCase()+fieldName.substring(1);
try {
method = beanClass.getMethod("get"+methodName, null);
} catch (SecurityException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
try {
method = beanClass.getMethod("is"+methodName, null);
} catch (SecurityException e1) {
e1.printStackTrace();
} catch (NoSuchMethodException e1) {
e1.printStackTrace();
}
}
methodArray[i] = method;
} return methodArray;
} private static <K, V> Map<K, V> bean2Map(Object javaBean) {
Map<K, V> ret = new HashMap<K, V>();
try {
Method[] methods = javaBean.getClass().getDeclaredMethods();
for (Method method : methods) {
if (method.getName().startsWith("get")) {
String field = method.getName();
field = field.substring(field.indexOf("get") + 3);
field = field.toLowerCase().charAt(0) + field.substring(1);
Object value = method.invoke(javaBean, (Object[]) null);
ret.put((K) field, (V) (null == value ? "" : value));
}
}
} catch (Exception e) {
}
return ret;
} public static Map objectToMap(Object o){
return objectToMap(o, "");
} private static Map objectToMap(Object o, String prefix)
{
Map ret = new HashMap();
if (o == null)
return ret;
try {
Map objDesc = PropertyUtils.describe(o); prefix = (!("".equals(prefix))) ? prefix + "." : "";
for (Iterator it = objDesc.keySet().iterator(); it.hasNext(); ) {
String key = it.next().toString();
Object val = objDesc.get(key);
if ((val != null) && (val instanceof CrmValueObject) && (!(o.equals(val))))
{
ret.putAll(objectToMap(val, prefix + key)); break;
}
ret.put(prefix + key, val);
}
} catch (Exception e) {
e.printStackTrace();
//logger.error(e);
}
//logger.debug("Object " + o + " convert to map: " + ret);
return ret;
} public static Map objectToMap(List fieldNameList, Object object)
{
Map ret = new HashMap();
for (Iterator it = fieldNameList.iterator(); it.hasNext(); ) {
String fieldName = (String)it.next();
String[] fs = fieldName.split(quote("."));
try {
Object o = object;
for (int i = 0; i < fs.length; ++i) {
Map objDesc = PropertyUtils.describe(o);
o = objDesc.get(fs[i]);
if (o == null)
break;
}
ret.put(fieldName, o);
} catch (Exception e) {
e.printStackTrace();
//logger.error(e);
}
}
return ret;
} public static String quote(String s)
{
int slashEIndex = s.indexOf("\\E");
if (slashEIndex == -1)
return "\\Q" + s + "\\E"; StringBuffer sb = new StringBuffer(s.length() * 2);
sb.append("\\Q");
slashEIndex = 0;
int current = 0;
while ((slashEIndex = s.indexOf("\\E", current)) != -1) {
sb.append(s.substring(current, slashEIndex));
current = slashEIndex + 2;
sb.append("\\E\\\\E\\Q");
}
sb.append(s.substring(current, s.length()));
sb.append("\\E");
return sb.toString();
}
}
java中两个对象间的属性值复制,比较,转为map方法实现的更多相关文章
- 【java】【反射】反射实现判断发生了修改操作,判断两个对象是否发生属性值的变更,判断两个List集合内对象的属性值是否发生变更
java的反射实现: 判断发生了修改操作,判断两个对象是否发生属性值的变更,判断两个List集合内对象的属性值是否发生变更 今日份代码: package com.sxd.streamTest; imp ...
- 判断java中两个对象是否相等
java中的基本数据类型判断是否相等,直接使用"=="就行了,相等返回true,否则,返回false. 但是java中的引用类型的对象比较变态,假设有两个引用对象obj1,obj2 ...
- Java中创建实例化对象的几种方式
Java中创建实例化对象有哪些方式? ①最常见的创建对象方法,使用new语句创建一个对象.②通过工厂方法返回对象,例:String s =String.valueOf().(工厂方法涉及到框架)③动用 ...
- java实现两台电脑间TCP协议文件传输
记录下之前所做的客户端向服务端发送文件的小项目,总结下学习到的一些方法与思路. 注:本文参考自<黑马程序员>视频. 首先明确需求,在同一局域网下的机器人A想给喜欢了很久的机器人B发送情书, ...
- [转] 有关java中两个整数的交换问题
转载申明:本文主要是用于自己学习使用,为了完善自己的只是框架,没有任何的商业目的. 原文来源:有关Java中两个整数的交换问题 如果侵权,麻烦告之,立刻删除. 在程序开发的过程,要交换两个变量的内容, ...
- Java学习笔记十四:如何定义Java中的类以及使用对象的属性
如何定义Java中的类以及使用对象的属性 一:类的重要性: 所有Java程序都以类class为组织单元: 二:什么是类: 类是模子,确定对象将会拥有的特征(属性)和行为(方法): 三:类的组成: 属性 ...
- java中的string对象深入了解
这里来对Java中的String对象做一个稍微深入的了解. Java对象实现的演进 String对象是Java中使用最频繁的对象之一,所以Java开发者们也在不断地对String对象的实现进行优化,以 ...
- java怎么比较两个实体类的属性值
分享一下比较两个实体类的工具包 package cn.mollie.utils; import java.beans.Introspector; import java.beans.PropertyD ...
- js中两个对象的比较
代码取自于underscore.js 1.8.3的isEqual函数. 做了一些小小的修改,主要是Function的比较修改. 自己也加了一些代码解读. <!DOCTYPE html> & ...
随机推荐
- Struts2五、Struts1与Struts2的区别
Struts1和Struts2的区别和对比: Action 类: • Struts1要求Action类继承一个抽象基类.Struts1的一个普遍问题是使用抽象类编程而不是接口,而struts2的Ac ...
- mysql数据库学习(一)--基础
一.简介 MySQL是一个关系型数据库管理系统,由瑞典MySQL AB 公司开发,目前属于 Oracle 旗下产品.MySQL 最流行的关系型数据库管理系统,在 WEB 应用方面MySQL是最好的 R ...
- Binary String Matching(kmp+str)
Binary String Matching 时间限制:3000 ms | 内存限制:65535 KB 难度:3 描述 Given two strings A and B, whose alp ...
- 2015-01-15百度地图API 新海量点
整理一下昨天写的百度地图 项目最开始写了一个百度地图,但是速度那慢的简直了 所以昨天将百度地图API的海量点 写了一下 1秒啊 o.o 厉害 OK 记下 此乃需要的js <!--添加百度地图- ...
- Java面试题之数据库三范式是什么
为了建立冗余较小.结构合理的数据库,设计数据库时必须遵循一定的规则.在关系型数据库中这种规则就称为范式.范式是符合某一种设计要求的总结.要想设计一个结构合理的关系型数据库,必须满足一定的范式. 在实际 ...
- T-SQL变量
T-SQL中变量分为全局变量和局部变量,分别使用@@和@前缀. 全局变量 常用的全局变量有@@VERSION .@@IDENTITY.@@ERROR.@@ROWCOUNT 用法 select @@VE ...
- 从Quartz时间设置问题说起
已经好久没有来写点啥了,原因有很多,不过最主要的还是自己很懒很懒,今天终于意识到问题的严重性了.所以就来了.今天的这个问题也是前不久刚刚遇到的问题.先不啰嗦,说重点了. 一.问题描述 定时任务项目发布 ...
- MIT6.828 JOS系统 lab2
MIT6.828 LAB2:http://pdos.csail.mit.edu/6.828/2014/labs/lab2/ LAB2里面主要讲的是系统的分页过程,还有就是简单的虚拟地址到物理地址的过程 ...
- Qt QtableView使用
ui->setupUi(this); ui->mainToolBar->hide(); tableView = new QTableView(this); // 设置表头 QStan ...
- op cache config
[opcache] ; dll地址 zend_extension=php_opcache.dll ; 开关打开 opcache.enable=1 ; 开启CLI opcache.enable_cli= ...