Dear all,
my problem is that I have to sort/group loads of beans in various
ways.
I'll do this by using java.util.Comparators.
I'll extract the data to be compared from my beans via getter methods.
I would like to use a generic approach for the comparator, i.e. you
simply pass it a getter method and it will compare based on the
natural ordering of the object returned by the getter.
Sample
<code>
public class SomeComp implements Comparator, Serializable {
Method getter;
public SomeComp(Method g){
this.getter = g;
}
/* (non-Javadoc)
* @see java.util.Comparator#compare(java.lang.Object,
java.lang.Object)
*/
public int compare(Object arg0, Object arg1) {
Comparable c0 = this.getter.invoke(arg0, null);
Comparable c1 = this.getter.invoke(arg1, null);
return c0.compareTo(c1);
}
}
</code>
However, I still have the problem of getting the correct getter method
from the bean. I thought the java.beans package would do this for me,
like
<code>Method getGetter(String propname)<code>
but could not find an easy way.
Any ideas??
Thx
Christian
Robert Klemme - 09 Dec 2004 12:32 GMT
> Dear all,
>
[quoted text clipped - 33 lines]
>
> Any ideas??
Use these methods in order:
http://java.sun.com/j2se/1.4.2/docs/api/java/beans/Introspector.html
http://java.sun.com/j2se/1.4.2/docs/api/java/beans/BeanInfo.html#getPropertyDesc
riptors()
http://java.sun.com/j2se/1.4.2/docs/api/java/beans/PropertyDescriptor.html#getRe
adMethod()
Kind regards
robert
Chris Riesbeck - 10 Dec 2004 22:13 GMT
> Dear all,
>
[quoted text clipped - 5 lines]
> simply pass it a getter method and it will compare based on the
> natural ordering of the object returned by the getter.
I'd recommend a simpler design. No need for Method or reflection.
> public class SomeComp implements Comparator, Serializable {
add "abstract"
> Method getter;
> public SomeComp(Method g){
> this.getter = g;
> }
Drop these lines. Add this line:
abstract public Comparable get(Object obj);
> public int compare(Object arg0, Object arg1) {
> Comparable c0 = this.getter.invoke(arg0, null);
> Comparable c1 = this.getter.invoke(arg1, null);
> return c0.compareTo(c1);
Replace with
public int compare(Object obj1, Object obj2) {
return get(obj1).compareTo(get(obj2));
}
> }
> }
Now you can sort a list of beans using any getter you want,
e.g., to sort a list of PersonName's by last name:
Collections.sort(names, new SomeComp() {
public Comparable get(Object obj) {
return ((PersonName) obj).getLastName();
}
});