程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> JAVA編程 >> 關於JAVA >> 應用Java反射完成JavaBean對象相反屬性復制並初始化目的對象為空的屬性的BeanUtils

應用Java反射完成JavaBean對象相反屬性復制並初始化目的對象為空的屬性的BeanUtils

編輯:關於JAVA

應用Java反射完成JavaBean對象相反屬性復制並初始化目的對象為空的屬性的BeanUtils。本站提示廣大學習愛好者:(應用Java反射完成JavaBean對象相反屬性復制並初始化目的對象為空的屬性的BeanUtils)文章只能為提供參考,不一定能成為您想要的結果。以下是應用Java反射完成JavaBean對象相反屬性復制並初始化目的對象為空的屬性的BeanUtils正文


有時遇到將數據傳輸對象轉換成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>() });
}
}
}
}

}

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved