General object sorting based on Java reflection

Source: Internet
Author: User
Tags collator

/**
* @ Title: objectsort. Java
* @ Package sort
* @ Description: Todo (describe the file in one sentence)
* @ Author youjianbo
* @ Date 2011-3-9 10:28:53 AM
* @ Version V1.0
*/
Package sort;

Import java. Lang. Reflect. method;
Import java. Math. bigdecimal;
Import java. Text. collationkey;
Import java. Text. collator;
Import java. util. arraylist;
Import java. util. collections;
Import java. util. comparator;
Import java. util. List;

Public class objectsort {

/**
* @ Param ARGs
*/
Public static void main (string [] ARGs ){
/**
*
* Author: youjianbo
* Date: 2008-6-27
* Purpose: sorts objects by one or more attributes.
* Java contains eight basic data types: Boolean, byte, Char, short, Int, float, douboe, and long.
* Only non-Boolean and byte attributes are compared, which are applicable to most application environments. If you have special requirements, modify them by yourself.
* You only need to pass in the object attribute list and list to be sorted.
***/
List arraydemo = new arraylist ();

Person p1 = new person ();
P1.setname ("James ");
P1.setage (200 );
P1.setsalary (100 );

Person P2 = new person ();
P2.setname ("Li Si ");
P2.setage (22 );
P2.setsalary (100 );

Person P3 = new person ();
P3.setname ("Wang Wu ");
P3.setage (25 );
P3.setsalary (1900 );

Person P4 = new person ();
P4.setname ("Zhao six ");
P4.setage (25 );
P4.setsalary (3000 );

Person P5 = new person ();
P5.setname ("Liu Qi ");
P5.setage (30 );
P5.setsalary (2000 );

Person P6 = new person ();
P6.setname ("Luba ");
P6.setage (25 );
P6.setsalary (2000 );

Person P7 = new person ();
P7.setname (" 9 ");
P7.setage (26 );
P7.setsalary (2000 );

Person P8 = new person ();
P8.setname (" ");
P8.setage (22 );
P8.setsalary (2000 );

Arraydemo. Add (P1 );
Arraydemo. Add (P2 );
Arraydemo. Add (P3 );
Arraydemo. Add (P4 );
Arraydemo. Add (P5 );
Arraydemo. Add (P6 );
Arraydemo. Add (P7 );
Arraydemo. Add (P8 );

// ********** Start to compare ********//
Commoncomparator comparator = new commoncomparator ();

// System. Out. println ("------ 0. Compare ---------" by name ---------");
// Comparator. setfields_user (New String [] {"name "});
// Collections. Sort (arraydemo, comparator );
// For (INT I = 0; I <arraydemo. Size (); I ++)
//{
// Person = (person) arraydemo. Get (I );
// System. out. println ("username:" + person. getname () + "Age:" + person. getage () + "monthly salary:" + person. getsalary ());
//}
// System. Out. println ("------ 1. Compare ---------" by age ---------");
// Comparator. setfields_user (New String [] {"Age "});
// Collections. Sort (arraydemo, comparator );
// For (INT I = 0; I <arraydemo. Size (); I ++)
//{
// Person = (person) arraydemo. Get (I );
// System. out. println ("username:" + person. getname () + "Age:" + person. getage () + "monthly salary:" + person. getsalary ());
//}
//
// System. Out. println ("------ 1. Compare the monthly salary from low to high ---------");
// Comparator. setfields_user (New String [] {"salary "});
// Collections. Sort (arraydemo, comparator );
// For (INT I = 0; I <arraydemo. Size (); I ++)
//{
// Person = (person) arraydemo. Get (I );
// System. out. println ("username:" + person. getname () + "Age:" + person. getage () + "monthly salary:" + person. getsalary ());
//}

// System. Out. println ("------ 1. Comparison of age and monthly salary ---------");
// Comparator. setfields_user (New String [] {"Age", "salary "});
// Collections. Sort (arraydemo, comparator );
// For (INT I = 0; I <arraydemo. Size (); I ++)
//{
// Person = (person) arraydemo. Get (I );
// System. out. println ("username:" + person. getname () + "Age:" + person. getage () + "monthly salary:" + person. getsalary ());
//}
//
// System. Out. println ("------ 1. Compare the monthly salary and age ---------");
// Comparator. setfields_user (New String [] {"salary", "Age "});
// Collections. Sort (arraydemo, comparator );
// For (INT I = 0; I <arraydemo. Size (); I ++)
//{
// Person = (person) arraydemo. Get (I );
// System. out. println ("username:" + person. getname () + "Age:" + person. getage () + "monthly salary:" + person. getsalary ());
//}
System. Out. println ("------ 1. Compare the age and monthly salary by name ---------");
Comparator. setfields_user (New String [] {"name", "Age", "salary "});
Collections. Sort (arraydemo, comparator );
For (INT I = 0; I <arraydemo. Size (); I ++)
{
Person = (person) arraydemo. Get (I );
System. out. println ("username:" + person. getname () + "--- age:" + person. getage () + "---- monthly salary:" + person. getsalary ());
}

System. Out. println ("------ 1. Compare monthly salary and age ---------");
Comparator. setfields_user (New String [] {"salary", "Age "});
Collections. Sort (arraydemo, comparator );
For (INT I = 0; I <arraydemo. Size (); I ++)
{
Person = (person) arraydemo. Get (I );
System. Out. println ("username:" + person. getname () + "Age:" + person. getage () + "monthly salary:" + person. getsalary ());
}
}

}

Class commoncomparator implements Comparator
{
/***
* @ Param
* The property of the comparison object is passed in the form of string [].
* The comparison object must comply with the JavaBean, that is, the set and get methods must be available.
**/
String [] fields_user = NULL;


Public String [] getfields_user (){
Return fields_user;
}
Public void setfields_user (string [] fields_user ){
This. fields_user = fields_user;
}
/**
* Define sorting rules
* Sort by more than one attribute
* This sorting is performed according to the order of attributes. The class is SQL order.
* That is, if the attribute at the same position is compared, it is stopped.
**/
Public int compare (Object obj1, object obj2)
{
// If no attribute exists, it is not sorted.
If (fields_user = NULL | fields_user.length <= 0)
{
Return 2; // do not compare
}
For (INT I = 0; I <fields_user.length; I ++)
{
Return comparefield (obj1, obj2, fields_user [I]);
}
Return 0;
}
/**
* @ Param fieldname
* Sort by attribute name
**/
Private Static int comparefield (Object O1, object O2, string fieldname)
{
Try
{
Object value1 = getfieldvaluebyname (fieldname, O1 );
Object value2 = getfieldvaluebyname (fieldname, O2 );

// -- String comparison
If (value1 instanceof string)
{
String V1 = getfieldvaluebyname (fieldname, O1). tostring ();
String v2 = getfieldvaluebyname (fieldname, O2). tostring ();
Collator mycollator = collator. getinstance ();
Collationkey [] keys = new collationkey [5];
Keys [0] = mycollator. getcollationkey (V1 );
Keys [1] = mycollator. getcollationkey (V2 );
Return (Keys [0]. compareto (Keys [1]);
// ------- Chinese characters may be faulty --------
// String V1 = getfieldvaluebyname (fieldname, O1). tostring ();
// String v2 = getfieldvaluebyname (fieldname, O2). tostring ();
//
// If (v1.compareto (V2)> 0 ){
// Return 1;
//} Else if (v1.compareto (V2) = 0 ){
// Return 0;
//} Else {
// Return-1;
//}
}
// -- Non-Comparative attributes are not compared
Else if ("Java. lang. boolean ". equals (value1.getclass (). getname () | "Java. lang. byte ". equals (value1.getclass (). getname ()))
{
Return 0;
} Else
{
Bigdecimal b1 = new bigdecimal (value1.tostring ());
Bigdecimal b2 = new bigdecimal (value2.tostring ());
Return b1.compareto (B2 );
}

} Catch (exception E)
{
System. Out. println ("-----------------------------------------------------------------------------");
System. Out. println ("--------- this attribute of the object does not exist or cannot be reflected on this security level. For details, see Java Doc --------");
System. Out. println ("-----------------------------------------------------------------------------");
E. printstacktrace ();
}
// Less
Return-1;
}
/**
* @ Param
* Fieldname attribute name
* OBJ object
* Obtain the attribute value through reflection.
**/
Private Static object getfieldvaluebyname (string fieldname, object OBJ)
{
Try
{
String letter = fieldname. substring (0, 1). touppercase ();
String methodstr = "get" + letter + fieldname. substring (1 );
Method method = obj. getclass (). getmethod (methodstr, new class [] {});

Object value = method. Invoke (OBJ, new object [] {});

Return value;
} Catch (exception E)
{
System. Out. println ("------------------------------------------------------");
System. Out. println ("--------- this" + fieldname + "property does not exist ----------------------");
System. Out. println ("------------------------------------------------------");
Return NULL;
}
}
}

Class person
{
Public Person (){}

Private string name;
Private int age;
Private long salary;

Public long getsalary (){
Return salary;
}
Public void setsalary (long salary ){
This. Salary = salary;
}
Public int getage (){
Return age;
}
Public void setage (INT age ){
This. Age = age;
}
Public String getname (){
Return name;
}
Public void setname (string name ){
This. Name = Name;
}
}

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.