Java uses reflection to sort Pojo and then turn string

Source: Internet
Author: User

Recently, due to business requirements, when communicating with other systems, it is required to sort the fields in the Pojo, and then convert the fields in ascending or descending order to a string, that is, the two parties perform the MD5 checksum in accordance with the same rules

According to the requirements of the use of the launch wrote a tool class, for everyone to share, for your reference

/**
* Sort by the field of the given class, then split with the specified delimiter <br/>
* @param instance instances of classes that need to be manipulated
* @param desc If True indicates descending, if false in ascending order
* @param the delimiter between separator fields
* @param the outer symbol of the Arraysymbol array begins the label, for example: The JSON array is used as a peripheral label for the inner element of the array, which means [
* @param the outer symbol of the Arrayendsymbol array begins the label, for example: The JSON array is used as the outer label of the inner element of the array, referred to here.
* @return
*/
public static String Objecttostringbyfieldorder (Object instance,boolean desc,string separator,string arraybeginsymbol , String Arrayendsymbol)
{
class<? Extends object> CLZSS = Instance.getclass ();

field[] Allfield = Clzss.getdeclaredfields ()///Note that this may contain all fields including public/protected/private, etc.

list<integer> orderlist = new arraylist<integer> ();//record each domain in Allfield location

Because of the business relationship here, only the domain of private scope is required, all name is sorted
for (int k=0;k<allfield.length;k++)
{
if (Modifier.isprivate (Allfield[k].getmodifiers ()))
{
if (k==0)
{
Orderlist.add (k);
Continue
}

Boolean isadd = false;
for (int t=0;t<orderlist.size (); t++)
{
if (DESC)//Descending
{
if (Allfield[k].getname (). CompareTo (Allfield[orderlist.get (t)].getname ()) >=0)
{
Isadd = true;
Orderlist.add (t, K);
Break
}
}else{//Ascending
if (Allfield[k].getname (). CompareTo (Allfield[orderlist.get (t)].getname ()) <=0)
{
Isadd = true;
Orderlist.add (t, K);
Break
}
}
}

if (!isadd)
{
Orderlist.add (k);
}
}
}

StringBuilder builder = new StringBuilder ();
Builder.append ("{");

String conversions based on well-ordered content
for (int m=0;m<orderlist.size (); m++)
{
if (m!=0)
{
Builder.append (separator);
}

Allfield[orderlist.get (M)].setaccessible (TRUE);//private, default is not allowed to access

Object value = null;

try {
Value = Allfield[orderlist.get (m)].get (instance);
} catch (Exception e) {
Logger.error ("Get value from the instance failed.the field name is" +allfield[orderlist.get (m)].getname (), E);
We don't do this right here, just jump over.
}

if (null = = value)
{
Continue
}

if (value instanceof list)//Some Pojo contain a list object, note that there may be object nesting objects, that is, the list nested list
{
Here is actually a recursive call
List inner_list = (list) value;

if (Inner_list.size () >0)
{
Note that this may also need to be customized, as the array may change in sequence as it is passed, remembering the previousJava TrainingTeacher said that if the MD5 is calculated, it will change, so the list should be sorted according to the business (no contribution to the system customization)

Builder.append (Allfield[orderlist.get (M)].getname () + "=" +arraybeginsymbol);
for (int n=0;n<inner_list.size (); n++)
{
Here you need to analyze whether the contents of the list are basic types, and if they are basic types, they are processed directly, and if not, recursive calls are required.
if (null = = Inner_list.get (n)) continue;

if (Inner_list.get (n) instanceof java.lang.String)//Because our side of the Pojo only string, so only to determine the string, if there are other basic types, you need to add
{
Builder.append (Inner_list.get (n));
}else{
Builder.append (Objecttostringbyfieldorder (Inner_list.get (n), DESC, separator,arraybeginsymbol,arrayendsymbol));
}

if (n< inner_list.size ()-1)
{
Builder.append (separator);
}
}

Builder.append (Arrayendsymbol);
}
}else{
Builder.append (Allfield[orderlist.get (M)].getname ()). Append ("="). Append (value);
}
}

Builder.append ("}");

System.err.println ("----------------------------------------" +builder.tostring ());

return builder.tostring ();
}

Test

First, create a simple people class:

public class People {

private String name;

private int age;

Private String sex;

Private String Mobile;

public String grade;

protected String Birthday;

Private list<string> friends;

Private List<child> Childs;

The setter getter will not write.

}

Create a child class:

public class Child {

Private String ChildName;

Private String Childmobile;

The setter getter will not write.
}

To start the test:

public static void Main (string[] args) throws IllegalArgumentException, Illegalaccessexception {

People p = new people ();

P.setname ("ZWB");

P.setage (25);

P.setsex ("male");

P.setgrade ("university");

P.setmobile ("1233456789");

P.setbirthday ("1990-11-27");

list<string> str = new arraylist<string> ();
Str.add ("Zhangsan");
Str.add ("Lisi");
Str.add ("Harry");

P.setfriends (str);

list<child> ch = new arraylist<child> ();

Child child1 = new Child ();

Child1.setchildmobile ("ChildMobile1");
Child1.setchildname ("childName1");

Child child2 = new Child ();

Child2.setchildmobile ("ChildMobile2");
Child2.setchildname ("childName2");

Ch.add (child1);
Ch.add (CHILD2);

P.setchilds (CH);

System.err.println ("-----:" +objecttostringbyfieldorder (P, True, "_", "[", "]"));
}

Operation Result:

----------------------------------------{Childname=childname1_childmobile=childmobile1}
----------------------------------------{Childname=childname2_childmobile=childmobile2}
----------------------------------------{sex= male _name=zwb_mobile=1233456789_friends=[zhangsan_lisi_ Harry]_childs=[{ CHILDNAME=CHILDNAME1_CHILDMOBILE=CHILDMOBILE1}_{CHILDNAME=CHILDNAME2_CHILDMOBILE=CHILDMOBILE2}]_AGE=25}
-----: {sex= male _name=zwb_mobile=1233456789_friends=[zhangsan_lisi_ Harry]_childs=[{childname=childname1_childmobile= CHILDMOBILE1}_{CHILDNAME=CHILDNAME2_CHILDMOBILE=CHILDMOBILE2}]_AGE=25}

Complete!

Java uses reflection to sort Pojo and then turn string

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.