blob: f8b1ccaf0d903ff25f43009705d519ac94a2f17b (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
|
/*
Wotonomy: OpenStep design patterns for pure Java applications.
Copyright (C) 2000 Intersect Software Corporation
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, see http://www.gnu.org
*/
package net.wotonomy.foundation.internal;
import java.io.Serializable;
import java.util.Comparator;
/**
* A Comparator that will sort elements based on the property specified in the
* constructor.
*
* @author michael@mpowers.net
* @author $Author: cgruber $
* @version $Revision: 893 $
*/
public class PropertyComparator<T> implements Comparator<T>, Serializable {
private static final long serialVersionUID = -3028294144521868334L;
private String property;
/**
* Standard constructor to configure the comparator.
*
* @param aProperty A property whose value is used to sort elements.
*/
public PropertyComparator(String aProperty) {
property = aProperty;
}
// interface Comparator
@SuppressWarnings("unchecked")
@Override
public int compare(Object o1, Object o2) {
Object v1 = Introspector.get(o1, property);
Object v2 = Introspector.get(o2, property);
if (v1 instanceof Comparable<?>) {
return ((Comparable<Object>) v1).compareTo(v2);
} else if (v2 instanceof Comparable) {
return ((Comparable<Object>) v2).compareTo(v1);
} else {
if (v1 == null) {
if (v2 == null) {
return 0; // both nulls are equal
}
return -1; // null is less than any object
} else if (v2 == null) {
return 1; // any object is greater than null
}
}
// last resort: compare string conversions
return v1.toString().compareTo(v2.toString());
}
@Override
public boolean equals(Object obj) {
return (obj instanceof PropertyComparator);
}
}
/*
* $Log$ Revision 1.2 2006/02/16 13:11:47 cgruber Check in all sources in
* eclipse-friendly maven-enabled packages.
*
* Revision 1.1.1.1 2000/12/21 15:52:07 mpowers Contributing wotonomy.
*
* Revision 1.2 2000/12/20 16:25:46 michael Added log to all files.
*
*
*/
|