Advertisement :
   Log In    OR    Register  
  Topics :  
RMI Example

Home >>> Coding Tips on Java >>> Java Reflection Comparator >>> Java Common Comparator
Struts Tutorials:
Struts2 Tag CheckBoxList
, Checkbox, Iterator, IF
Struts2 Tag Library Example Struts2 Tiles Example Struts2 Tiles I18N Example Struts2 Questions Struts Tiles I18N Example Struts Eclipse MVC Struts2 Tags Struts2 Example and Tutorial Struts MVC Struts2 Validation
Hibernate Tutorials: Hibernate Case Study Class Hierarchy Persist Example Using Hibernate Interceptor Hibernate Questions with Answer Hibernate Many-to-Many Mapping Example Hibernate one-to-many Mapping Example Hibernate and ORM tools Spring Hibernate Example Hibernate SessionFactory Example Hibernate Mapping Class Hierarchy Hibernate Questions Hibernate SessionFactory Questions Spring Hibernate Example: Spring Hibernate Case Study

Written By : Amit
Title :
Composite keys in Hashtable
Description : key and value pair
More...


Written By : Amit
Title :
Customizing JTree using Swing
Description : AWT using Java Technology
More...


Written By : Amit
Title :
Event handling and Java Technology
Description : Event handling and Java Technology
More...


Written By : admin
Title :
Using Final Keyword
Description : Example on using Final Keyword in Java code
More...


Written By : Amit
Title :
In memory AWT Image Creation
Description : Java Code
More...


Written By : Amit
Title :
Java Integral Types
Description : Java Types with Bit size
More...

Tags/Keywords : Java Comparator, Reflection, Common Comparator, Java Reflection, example, code, article, tutorial
Author : ISHTEK
Date (Year/Month/Date): 2009-07-15 Comparator using Java Technology and Reflection API

Please be informed that NONE of the design/code from this
page is claiming to be some sort of best practices and we DO NOT expect
any of our visitor/reader of this page to assume this as some sort of
best practice for any context and should not be using this 
as it is without appropriate evaluation to their, so to say, 
specific programming context.

This page intends only to provide bit and piece of known ways  for
doing some sort of example and may not be fit for any other purpose.

How to write a comparator that can be used for any class that is
to be sorted, without changing the comparator or the class to be compared?

Suppose one has to sort all student objects in a list, then we know this can be
done by using either by defining java.lang.Comparable or 
java.util.Comparator interfaces.
By using java.util.Collections.sort method, one can do sorting on list of 
objects.

In this article I have tried to come up with another ways of providing
comparator that can be used with any number of JavaBeans, those are to be
comparated and sorted. By using this approach, I think, one should be able
to reduce somplexities of defining compareTo methods in many POJO, and
not to define many comparators for multiple POJOs (Those are to be sorted).

Explanation :
In this very scenario, the Comparator has to use reflection from java.lang.reflect
package to dynamically/runtime detection of the corresponding field to be used
for sorting and compare. Discussing with an example will help us understand this.

Example case study:
let us take the Student class as the class to be compared for sorting
based on two field "name" and "age".

Student.java
--------------------------------------
 private String name;
 private int age;
 public Student(String name, int age)
 {
 this.name = name;
 this.age = age;
 }
 public String getName()
 {
 return name;
 }
 public void setName(String name)
 {
 this.name = name;
 }
 public int getAge()
 {
 return age;
 }
 public void setAge(int age)
 {
 this.age = age;
 }
---------------------------------------

This Student class doesn't implement java.lang.Comparable interface, then
the comparator (suppose the name is TestComparator):
This TestComparator implements java.util.Comparator, and implement compareTo
method. Input to this TestComparator are the field (on which the sorting will
take place), and the type of sorting (Whether ascending or descending).

There are two important information required for feeding required values to the 
compareTo method, one is the value of the field and the other one is the Java 
Type of this field. So is sorting is to be done based on Student.name,
then required information are
  • value of name field - "test name"
  • type of name field - java.lang.String
  • And if sorting is to be done based on Student.age, then these are
  • value of age field - 23 (example age of student)
  • type of age field - int
  • To get these two inputs, we have two methods getValue and getType --------------------------------------- private Object getValue(Object a) { Object obj = null; Class[] obj1 = null; Object[] obj2 = null; String methodName = "get"+fieldName.replace(fieldName.substring(0,1) ,fieldName.substring(0,1).toUpperCase()); try{ obj = a.getClass().getMethod(methodName,obj1).invoke(a,obj2); }catch(Exception ex){ ex.printStackTrace(); } return obj; } ---------------------------------------- fieldName - the field to be used for sorting. methodName - to get the accessible method name for the attribute, like if attribute name is "age", the methodName will be "getAge". obj - gets the value that the methodName returns from object. ---------------------------------------- private Object getType(Object a) { Class[] obj1 = null; Object obj = null; String methodName = "get"+fieldName.replace(fieldName.substring(0,1), fieldName.substring(0,1).toUpperCase()); try{ obj = a.getClass().getMethod(methodName,obj1).getReturnType() .getName().toString(); }catch(Exception ex){ ex.printStackTrace(); } return obj; } ----------------------------------------- This method returns the Java type of the methodName. Client code using Java Technology, includes creation of Student Object multiple times 1. Student student1=new Student("name1",34); Student student2=new Student("aname2",64); Student student3=new Student("zname3",27); 2. create a list List list = new ArrayList(); 3. add all the three students list.add(student1); list.add(student2); list.add(student3); 4. sort this list using Collections Collections.sort(list,new TestComparator("name",1)); 1 = for descending order 0 = for ascending 5. Not this list is sorted Students by name in descending order. Now the complete source of this TestComparator is as follows: TestComparator.java
    
    /**
    *  This source is provided as is, without any warranty
    *  and /or guaranty of any kind.
    *  Copyright (C) 2008, ISHTIAK, All Rights Reserved.
    *  You can use it for Personal Learning purpose only.
    *  source: http://www.interview-questions-tips-forum.net
    */
    
    import java.util.Comparator;
    
    public class TestComparator implements Comparator
    {
        private String fieldName;
        public TestComparator(String argFieldName, int a) {
            this.fieldName = argFieldName;
    	}
        private Object getValue(Object a)
        {
          Object obj = null;
          Class[] obj1 = null;
          Object[] obj2 = null;
          String methodName = "get"+fieldName.replace(fieldName.substring(0,1)
                                     ,fieldName.substring(0,1).toUpperCase());
    
         try{
            obj = a.getClass().getMethod(methodName,obj1).invoke(a,obj2);
    
         }catch(Exception ex){
            ex.printStackTrace();
         }
          return obj;
       }
       private Object getType(Object a)
       {
         Class[] obj1 = null;
         Object obj = null;
         String methodName = "get"+fieldName.replace(fieldName.substring(0,1),
         fieldName.substring(0,1).toUpperCase());
         try{
             obj = a.getClass().getMethod(methodName,obj1)
                               .getReturnType().getName().toString();
         }catch(Exception ex){
           ex.printStackTrace();
         }
         return obj;
       }
    
      public int compare(Object obj1, Object obj2) {
    	  int status=0;
    	  //System.out.println(getType(obj2));
        if(getType(obj2).equals("java.lang.String")) {
    		status = ((String)getValue(obj1)).compareTo((String)getValue(obj2));
    	} 
        if(getType(obj2).equals("int")) {
    		status = ((Integer)getValue(obj1)).compareTo((Integer)getValue(obj2));
    	} 
    	return status;
      }
    }
    
    The client to test this application is as follows: TestClient.java /** * This source is provided as is, without any warranty * and /or guaranty of any kind. * Copyright (C) 2008, ISHTIAK, All Rights Reserved. * You can use it for Personal Learning purpose only. * source: http://www.interview-questions-tips-forum.net */
    import java.util.*;
    public class TestClient {
      public TestClient() {
    	      //Some random test data.
    
    	  Student student1=new Student("name1",34);
    	  Student student2=new Student("aname2",64);
    	  Student student3=new Student("zname3",27);
    
        List list = new ArrayList();
        list.add(student1);
    		list.add(student2);
    		list.add(student3);
        //test code for sorting Students based on name field.
        Collections.sort(list,new TestComparator("name",1));
        System.out.println("Sorted based on Student.name :");
        Iterator  itr = list.iterator();
    	while(itr.hasNext()) {
    		System.out.println(((Student)itr.next()).getName());
    	}
    
        //test code for sorting Students based on age field.
        Collections.sort(list,new TestComparator("age",1));
        System.out.println("Sorted based on Student.age :");
        Iterator  itr1 = list.iterator();
    	while(itr1.hasNext()) {
    		System.out.println(((Student)itr1.next()).getAge());
    	}
      }
      public static void main(String args[]) {
        new TestClient();
      }
    }
    
    As of now this code is at very preliminary stage, and I am working on it to make this a framework suitable enough to be used in any project/product. if interested in participating with this initiative, please provide your comments (those are really valuable to me).
    
    
    	

    Commented By ->
    mengistu
    how to program class student 

    Commented By ->
    Ishtek
    I think you can write the class student as follows:
    
    package xyz;
    
    public class Student {
    
    ...
    ...
    
    }
    
    where by the dotted lines can be replaced with the
    code from this page.
    Are you interested in solving a very interesting Technology Stack while Playing this Game          

    Please write your Comment on this Matter
    (This will be visible if found suitable):
    Name: *
    Email (will not be displayed): *
    Matter: *
    30,30
    Enter bigger number from above :*
    Home >>> Coding Tips on Java >>> Java Reflection Comparator >>> Java Common Comparator
    Visitor/User referred related external URL:
    (Visible upon review and approved by this site Administrator)
    
    Referred By Name *:
    Resource URL *: (e.g, URL should be starting with http://www.-----.---)
     
    Resource Short Description *:
    25,23
    Enter bigger number from above : *

    Please log in to add or reply to any matter<- requires login
    Log in or Register
    Copyright © 2008-2009, Interview-Questions-Tips-Forum, All Rights Reserved.
    CONTACT    PRIVACY POLICY    DISCLAIMER
    Terms of Use and Disclaimer :
    
    This web site provides some of the information about various technologies, example 
    code, tips, tutorials etc. Like any printed materials, content of these pages may 
    become out of date over a period of time. Therefore all visitor/users of this web 
    site are requested/advised to refer to the originating parties/sources for the 
    latest changes and happenings for detailed information. This information is not 
    intended to be a substitute for the original reference provided by the originating 
    parties/sources.
    
    By accessing and using this website in any ways, including, without
    limitation, browsing the website pages, using any information, using any content and/or 
    downloading any materials, you agree to and are bound by the terms of use 
    described in this page and Usage Terms and Conditions. 
    If you do not agree to all of 
    the terms and conditions contained in the terms of use described in this
    page and Usage Terms and Conditions, do not use this 
    website in any manner. If you are using the website on behalf of your 
    employer, you represent that you are authorized to accept these Terms of Use 
    on your employer's behalf.
    
    All Trademarks are property of their respective owner. Appropriate measure is being
    taken for providing accurate and up-to-date information but like any printed materials,
    these blog(s)/contents may eventually be outdated one day, so if you are using any 
    of these information, please refer original content/documentation from respective sources. 
    And under no circumstances shall the Author of these contents and/or this web site
    be liable for any loss, damage, expense incurred or suffered which is claimed to have
    occurred because of usage of the contents of this web site.
    If you have any questions/queries/feedback/suggestions then please write to this web
    site owner at contact.