有时遇到将数据传输对象转换成JSON串会将属性值为空的属性去掉,利用Java反射实现JavaBean对象数据传输对象的相同属性复制并初始化数据传输对象属性为空的属性,然后转换成JSON串

package com.banksteel.util;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;

/**
* @description: copy对象属性工具类
* @projectName:banksteel-util
* @className:BeanUtil.java
* @see: com.banksteel.util
* @author:
* @createTime:2017年2月7日 上午9:15:23
* @version 3.0.0
*/
public class BeanUtils
{
private final static String GETTER = "get";
private final static String SETTER = "set";
private final static String IS = "is";
private final static String INTEGER = "java.lang.Integer";
private final static String DOUBLE = "java.lang.Double";
private final static String LONG = "java.lang.Long";
private final static String STRING = "java.lang.String";
private final static String SET = "java.util.Set";
private final static String LIST = "java.util.List";
private final static String MAP = "java.util.Map";

/**
* 对象之间相同属性复制
*
* @param source
* 源对象
* @param target
* 目标对象
*/
public static void copyProperties(Object source, Object target)
{
try
{
copyExclude(source, target, null);
}
catch (Exception e)
{
e.printStackTrace();
}
try
{
initBeanProperties(target);
}
catch (Exception e)
{
e.printStackTrace();
}
}

/**
* @description: 对象之间相同属性复制
* @param source
* 源对象
* @param target
* 目标对象
* @param excludsArray
* 排除属性列表
* @author:
* @createTime:2017年2月8日 下午5:07:11
*/
public static void copyPropertiesExclude(Object source, Object target, String[] excludsArray)
{
try
{
copyExclude(source, target, excludsArray);
}
catch (Exception e)
{
e.printStackTrace();
}
try
{
initBeanProperties(target);
}
catch (Exception e)
{
e.printStackTrace();
}
}

/**
* @description: 对象之间相同属性复制
* @param source
* 源对象
* @param target
* 目标对象
* @param includsArray
* 包含的属性列表
* @author:
* @createTime:2017年2月8日 下午5:07:11
*/
public static void copyPropertiesInclude(Object source, Object target, String[] includsArray)
{
try
{
copyInclude(source, target, includsArray);
}
catch (Exception e)
{
e.printStackTrace();
}
try
{
initBeanProperties(target);
}
catch (Exception e)
{
e.printStackTrace();
}
}

private static boolean isGetter(Method method)
{
String methodName = method.getName();
Class<?> returnType = method.getReturnType();
Class<?> parameterTypes[] = method.getParameterTypes();
if (returnType.equals(void.class))
{
return false;
}
if ((methodName.startsWith(GETTER) || methodName.startsWith(IS)) && parameterTypes.length == 0)
{
return true;
}
return false;
}

private static boolean isSetter(Method method)
{
String methodName = method.getName();
Class<?> parameterTypes[] = method.getParameterTypes();

if (methodName.startsWith(SETTER) && parameterTypes.length == 1)
{
return true;
}
return false;
}

/**
* 复制对象属性
*
* @param source
* @param target
* @param excludsArray
* 排除属性列表
* @throws Exception
*/
private static void copyExclude(Object source, Object target, String[] excludsArray) throws Exception
{
List<String> excludesList = null;

if (excludsArray != null && excludsArray.length > 0)
{
excludesList = Arrays.asList(excludsArray); // 构造列表对象
}
Method[] sourceMethods = source.getClass().getDeclaredMethods();
Method[] targetMethods = target.getClass().getDeclaredMethods();
Method sourceMethod = null, targetMethod = null;
String sourceMethodName = null, targetMethodName = null;

for (int i = 0; i < sourceMethods.length; i++)
{

sourceMethod = sourceMethods[i];
sourceMethodName = sourceMethod.getName();

if (!isGetter(sourceMethod))
{
continue;
}
// 排除列表检测
if (excludesList != null && excludesList.contains(sourceMethodName.substring(3).toLowerCase()))
{
continue;
}
targetMethodName = SETTER + sourceMethodName.substring(3);
targetMethod = findMethodByName(targetMethods, targetMethodName);

if (targetMethod == null)
{
continue;
}

if (!isSetter(targetMethod))
{
continue;
}

Object value = sourceMethod.invoke(source, new Object[0]);

if (value == null)
{
continue;
}
// 集合类判空处理
if (value instanceof Collection)
{
Collection<?> newValue = (Collection<?>) value;

if (newValue.size() <= 0)
{
continue;
}
}

targetMethod.invoke(target, new Object[]
{ value });
}
}

private static void copyInclude(Object source, Object target, String[] includsArray) throws Exception
{
List<String> includesList = null;

if (includsArray != null && includsArray.length > 0)
{
includesList = Arrays.asList(includsArray);
}
else
{
return;
}
Method[] sourceMethods = source.getClass().getDeclaredMethods();
Method[] targetMethods = target.getClass().getDeclaredMethods();
Method sourceMethod = null, targetMethod = null;
String sourceMethodName = null, targetMethodName = null;

for (int i = 0; i < sourceMethods.length; i++)
{
sourceMethod = sourceMethods[i];
sourceMethodName = sourceMethod.getName();

if (!isGetter(sourceMethod))
{
continue;
}

// 排除列表检测
String str = sourceMethodName.substring(3);

if (!includesList.contains(str.substring(0, 1).toLowerCase() + str.substring(1)))
{
continue;
}

targetMethodName = SETTER + sourceMethodName.substring(3);
targetMethod = findMethodByName(targetMethods, targetMethodName);

if (targetMethod == null)
{
continue;
}

if (!isSetter(targetMethod))
{
continue;
}

Object value = sourceMethod.invoke(source, new Object[0]);

if (value == null)
{
continue;
}

// 集合类判空处理
if (value instanceof Collection)
{
Collection<?> newValue = (Collection<?>) value;

if (newValue.size() <= 0)
{
continue;
}
}

targetMethod.invoke(target, new Object[]
{ value });
}
}

/**
* 从方法数组中获取指定名称的方法
*
* @param methods
* @param name
* @return
*/
private static Method findMethodByName(Method[] methods, String name)
{
for (int j = 0; j < methods.length; j++)
{
if (methods[j].getName().equals(name))
{

return methods[j];
}
}
return null;
}

private static boolean isTrimEmpty(String str)
{

return (str == null) || (str.trim().isEmpty());
}

/**
* @description: 初始化对象为空的属性
* @param obj
* @throws Exception
* @author:
* @createTime:2017年2月7日 下午3:31:14
*/
private static void initBeanProperties(Object obj) throws Exception
{
Class<?> classType = obj.getClass();
for (Field field : classType.getDeclaredFields())
{
// 获取对象的get,set方法
String getMethodName = GETTER + field.getName().substring(0, 1).toUpperCase() + field.getName().substring(1);
String setMethodName = SETTER + field.getName().substring(0, 1).toUpperCase() + field.getName().substring(1);
// 调用对象的get方法获取属性值
Method getMethod = classType.getDeclaredMethod(getMethodName, new Class[]
{});
Object value = getMethod.invoke(obj, new Object[]
{});

// String fieldType = field.getType().toString();
String fieldType = field.getType().toString();
if (value == null && !isTrimEmpty(fieldType))
{
// 调用对象的set方法把属性值初始化
if (fieldType.contains(INTEGER))
{
Method setMethod = classType.getDeclaredMethod(setMethodName, new Class[]
{ field.getType() });
setMethod.invoke(obj, new Object[]
{ 0 });
}
else if (fieldType.contains(DOUBLE))
{
Method setMethod = classType.getDeclaredMethod(setMethodName, new Class[]
{ field.getType() });
setMethod.invoke(obj, new Object[]
{ 0.0 });
}
else if (fieldType.contains(LONG))
{
Method setMethod = classType.getDeclaredMethod(setMethodName, new Class[]
{ field.getType() });
setMethod.invoke(obj, new Object[]
{ 0L });
}
else if (fieldType.contains(STRING))
{
Method setMethod = classType.getDeclaredMethod(setMethodName, new Class[]
{ field.getType() });
setMethod.invoke(obj, new Object[]
{ "" });
}
else if (fieldType.contains(SET))
{
Method setMethod = classType.getDeclaredMethod(setMethodName, new Class[]
{ field.getType() });
setMethod.invoke(obj, new Object[]
{ new HashSet<Object>() });
}
else if (fieldType.contains(LIST))
{
Method setMethod = classType.getDeclaredMethod(setMethodName, new Class[]
{ field.getType() });
setMethod.invoke(obj, new Object[]
{ new ArrayList<Object>() });
}
else if (fieldType.contains(MAP))
{
Method setMethod = classType.getDeclaredMethod(setMethodName, new Class[]
{ field.getType() });
setMethod.invoke(obj, new Object[]
{ new HashMap<Object, Object>() });
}
}
}
}

}

利用Java反射实现JavaBean对象相同属性复制并初始化目标对象为空的属性的BeanUtils的更多相关文章

  1. 通过java反射得到javabean的属性名称和值参考

    通过java反射得到javabean的属性名称和值 Field fields[]=cHis.getClass().getDeclaredFields();//cHis 是实体类名称 String[] ...

  2. 利用Java反射根据类的名称获取属性信息和父类的属性信息

    代码: import java.lang.reflect.Field; import java.util.ArrayList; import java.util.Arrays; import java ...

  3. 利用JAVA反射机制设计通用的DAO

    利用JAVA反射机制设计一个通用的DAO 反射机制 反射机制指的是程序在运行时能够获取自身的信息.在java中,只要给定类的名字,    那么就可以通过反射机制来获得类的所有信息. 反射机制创建类对象 ...

  4. 利用java反射机制 读取配置文件 实现动态类载入以及动态类型转换

    作者:54dabang 在spring的学习过程之中,我们能够看出通过配置文件来动态管理bean对象的优点(松耦合 能够让零散部分组成一个总体,而这些总体并不在意之间彼此的细节,从而达到了真正的物理上 ...

  5. 利用Java反射机制对实体类的常用操作工具类ObjectUtil

    代码: ObjectUtil类: import java.lang.reflect.Field; import java.math.BigDecimal; import java.text.Simpl ...

  6. 利用java反射调用类的的私有方法--转

    原文:http://blog.csdn.net/woshinia/article/details/11766567 1,今天和一位朋友谈到父类私有方法的调用问题,本来以为利用反射很轻松就可以实现,因为 ...

  7. 利用Java反射机制将Bean转成Map

    import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang ...

  8. Java反射获取class对象的三种方式,反射创建对象的两种方式

    Java反射获取class对象的三种方式,反射创建对象的两种方式 1.获取Class对象 在 Java API 中,提供了获取 Class 类对象的三种方法: 第一种,使用 Class.forName ...

  9. 不使用BeanUtils,利用Java反射机制:表单数据自动封装到JavaBean

    在百度搜“java反射 将表单数据自动封装到javabean ”,第一页显示的都是一样的代码,都是利用导入第三方jar包<commons-beanutils>和<commons-lo ...

随机推荐

  1. ator自动生成mybatis配置和类信息

    generator自动生成mybatis的xml配置.model.map等信息: 1.下载mybatis-generator-core-1.3.2.jar包.        网址:http://cod ...

  2. SpringMVC之RequestMappingHandlerMapping

    <mvc:annotation-driven content-negotiation-manager="" enable-matrix-variables="tru ...

  3. js--常量,变量

    常量 内存中的一个的固定的地址,其中的数值也是固定的 变量 内存的一个地址,其中的内容有我们更改维护 值类型与引用类型 改变值类型的变量时,影响值的变量 全大写的名称一般为常量 var a = 1 v ...

  4. Go语言学习笔记一: Hello World

    Go语言学习笔记一: Hello World 听说Go语言又快又简单.即具有C语言的运行速度,又具有Python语言的开发效率,不知道真的假的.所以特意来学学这门"老"语言. 下载 ...

  5. rails命令行命令

    x.指定端口启动rails项目 ruby script/server webrick -p 3000 ------------------------------------------------- ...

  6. nextval 遍历ResultSet,行列要从1开始

    nextval nextval与序列关联,表示下一个,如:创建里一个序列seq_1:#序列一般表示第几行,起标识作用create sequence seq_1 increment by 1 start ...

  7. java调用c/c++代码简单实现以及遇见的坑

    以下内容均来自互联网,感谢你们的分享,我只是使用的时候看这方便,可以称呼我“搬运工” 如有不合适的地方请与我联系,我会及时改正 首先你可能会遇见以下错误 第一个错误是你在vs编译器没有选择使用rele ...

  8. angularjs ui-grid cellTemplate checkbox ng-checked

    {     name: '@Localizer["ActiveInd"]',     field: 'ActiveInd',     enableSorting: false,   ...

  9. linux 图解常用的云运维监控工具

    随着新技术的不断发展,云服务已经互联网企业的必须,但是长期以来会存在传统物理主机和云主机.私有云和公有云并存的状态.此外,互联网企业的发展速度非常快,小米.滴滴出行等很多企业都是在短短几年内发展起来的 ...

  10. 如鹏网学习笔记(七)HTML基础

    HTML笔记 一.HTML简介 1,HTML (Hyper Text Mark-up Language) 超文本标记语言,是一种编程语言,也可以说是一种标准.规范. 2,HTML提供了一系列标记(标签 ...