View Javadoc

1   /*
2    * Copyright 2004-2009 the original author or authors.
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    *      http://www.apache.org/licenses/LICENSE-2.0
9    *
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.springmodules.validation.util.condition.range;
18  
19  import java.math.BigDecimal;
20  
21  
22  /**
23   * A comparator that compares {@link Comparable} instances but treats comparison of {@link Number} instances
24   * in a special manner. In order to support comparison of numbers regardless of their type, this comparator transform
25   * the numbers to {@link BigDecimal} and then does the comparison.
26   *
27   * @author Uri Boness
28   */
29  public class NumberAwareComparableComparator extends ComparableComparator {
30  
31      /**
32       * Compares the two given objects. Expects both of them to be {@link Comparable} instances.
33       *
34       * @see ComparableComparator#compare(Object, Object)
35       */
36      public int compare(Object o1, Object o2) {
37          if (Number.class.isInstance(o1) && Number.class.isInstance(o2)) {
38              return compareNumbers((Number) o1, (Number) o2);
39          }
40          return super.compare(o1, o2);
41  
42      }
43  
44      /**
45       * Compares the two given numbers. These numbers are compared regardless of their type.
46       *
47       * @param n1 The first number.
48       * @param n2 The second number.
49       * @return possitive number if <code>n1 &gt; n2</code>, negative number if <code>n1 &lt; n2</code>, or 0 (Zero) if
50       *         <code>n1 == n2</code>.
51       */
52      protected int compareNumbers(Number n1, Number n2) {
53          BigDecimal bd1 = new BigDecimal(n1.toString());
54          BigDecimal bd2 = new BigDecimal(n2.toString());
55          return bd1.compareTo(bd2);
56      }
57  
58  }