01: /*
02: * Copyright 2002-2006 the original author or authors.
03: *
04: * Licensed under the Apache License, Version 2.0 (the "License");
05: * you may not use this file except in compliance with the License.
06: * You may obtain a copy of the License at
07: *
08: * http://www.apache.org/licenses/LICENSE-2.0
09: *
10: * Unless required by applicable law or agreed to in writing, software
11: * distributed under the License is distributed on an "AS IS" BASIS,
12: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13: * See the License for the specific language governing permissions and
14: * limitations under the License.
15: */
16:
17: package org.springframework.core;
18:
19: import java.util.Comparator;
20:
21: /**
22: * {@link Comparator} implementation for {@link Ordered} objects,
23: * sorting by order value ascending (resp. by priority descending).
24: *
25: * <p>Non-<code>Ordered</code> objects are treated as greatest order
26: * values, thus ending up at the end of the list, in arbitrary order
27: * (just like same order values of <code>Ordered</code> objects).
28: *
29: * @author Juergen Hoeller
30: * @since 07.04.2003
31: * @see Ordered
32: * @see java.util.Collections#sort(java.util.List, java.util.Comparator)
33: * @see java.util.Arrays#sort(Object[], java.util.Comparator)
34: */
35: public class OrderComparator implements Comparator {
36:
37: public int compare(Object o1, Object o2) {
38: int i1 = getOrder(o1);
39: int i2 = getOrder(o2);
40:
41: // Direct evaluation instead of Integer.compareTo to avoid unnecessary object creation.
42: return (i1 < i2) ? -1 : (i1 > i2) ? 1 : 0;
43: }
44:
45: /**
46: * Determine the order value for the given object.
47: * <p>The default implementation checks against the {@link Ordered}
48: * interface. Can be overridden in subclasses.
49: * @param obj the object to check
50: * @return the order value, or <code>Ordered.LOWEST_PRECEDENCE</code> as fallback
51: */
52: protected int getOrder(Object obj) {
53: return (obj instanceof Ordered ? ((Ordered) obj).getOrder()
54: : Ordered.LOWEST_PRECEDENCE);
55: }
56:
57: }
|