Advertisement :
   Log In    OR    Register  
  Topics :  
RMI Example

Home >>> Coding Tips on Java >>> Comparator and Reflection using Java >>> Java and CompareTo
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 :
Comparator and Reflection using Java
Description : Java and CompareTo
More...


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...

Tags/Keywords : Java-and-CompareTo - Comparator-and-Reflection-using-Java - Coding-Tips-on-Java Example
Author : Amit
Date (Year/Month/Date): 2009-01-25 Comparator and Reflection using Java Technology

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.

 
Advertisement :
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?

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.
Using the same example as that of the 
earlier Question,
let us take the Student class
as the class to be compared for sorting
based on two field "name" and "age".

--------------------------------------
 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.
    Advertisement :
     
    Author of this article/writeup has expressed his/her willingness
    to help or guide users with any technical difficulties he/she faces while working with the example code environment setting up, running and resolving any such exception raised during compile or at runtime. You may ask for any technical doubt or seek technical help related to this article by using following form to reach for technical help from the Author for FREE. This article's Author shall be reading your request and responding within reasonable time (no resolution timeframe defined as such).
    
    
    	

    Commented By ->
    kalpana
    I want to add the value of hashtable at runtime for eg.,
    if there is already 5 elements i want to add my element as the sixth one during runtime.
        looking forward for your help
           Advance Thanks

    Commented By ->
    Dave
    Is there available complete example code of the general
    comparator...I cant yet figure out what to do exactly
    in the TestComparator.compare method when I got back
    the type and value of the objects...otherwise its been 
    helpful since I'm new to reflection stuff.
    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: *
    32,37
    Enter bigger number from above :*
    Home >>> Coding Tips on Java >>> Comparator and Reflection using Java >>> Java and CompareTo
    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 *:
    31,16
    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.