Using Java reflection to implement the same properties of the JavaBean object copy and initialize the beanutils of the property that the target object is empty

Source: Internet
Author: User
Tags list of attributes

Sometimes encountering a property that converts a data transfer object to a JSON string removes an attribute with an empty property value, uses Java reflection to implement the same properties of the JavaBean Object data Transfer object, copies and initializes the property with null properties for the data Transfer object, and then converts it to a JSON string

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 Object Properties Tool class
* @projectName: Banksteel-util
* @className: Beanutil.java
* @see: Com.banksteel.util
* @author:
* @createTime: February 7, 2017 morning 9:15:23
* @version 3.0.0
*/
public class Beanu TILs
{
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";

/**
* Same property copy between objects
*
* @param source
* Source Object
* @param target
* Target Object
*/
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: Copy the same property between objects
* @param source
* Source Object
* @param target
* Target Object
* @param Excludsarray
* Exclude Attribute List
* @author:
* @createTime: February 8, 2017 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: Copy the same property between objects
* @param source
* Source Object
* @param target
* Target Object
* @param Includsarray
* Included list of attributes
* @author:
* @createTime: February 8, 2017 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)
{
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)
{
String methodName = Method.getname ();
class<?> parametertypes[] = Method.getparametertypes ();

if (Methodname.startswith (SETTER) && parametertypes.length = = 1)
{
return true;
}
return false;
}

/**
* Copy Object Properties
*
* @param source
* @param target
* @param Excludsarray
* Exclude Attribute List
* @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); Constructing list objects
}
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
}
Exclusion List Detection
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
}
The collection class is sentenced to empty processing
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
}

Exclusion List Detection
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
}

The collection class is sentenced to empty processing
if (value instanceof Collection)
{
collection<?> newvalue = (collection<?>) value;

if (newvalue.size () <= 0)
{
Continue
}
}

Targetmethod.invoke (target, new object[]
{value});
}
}

/**
* method to get the specified name from the method array
*
* @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: Initialize the object to an empty property
* @param obj
* @throws Exception
* @author:
* @createTime: February 7, 2017 3:31:14
*/
private static void Initbeanproperties (Object obj) throws Exception
{
class<?> ClassType = Obj.getclass ();
For (Field Field:classType.getDeclaredFields ())
{
Get the Get,set method of an object
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);
Call the object's Get method to get the property value
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))
{
The set method of the calling object initializes the property value.
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> ()});
}
}
}
}

}

Using Java reflection to implement the same properties of the JavaBean object copy and initialize the beanutils of the property that the target object is empty

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.