View Javadoc

1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one or more
3    * contributor license agreements.  See the NOTICE file distributed with
4    * this work for additional information regarding copyright ownership.
5    * The ASF licenses this file to You under the Apache License, Version 2.0
6    * (the "License"); you may not use this file except in compliance with
7    * the License.  You may obtain a copy of the License at
8    * 
9    *      http://www.apache.org/licenses/LICENSE-2.0
10   * 
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the License for the specific language governing permissions and
15   * limitations under the License.
16   */
17  package org.apache.commons.lang.enums;
18  
19  import java.lang.reflect.InvocationTargetException;
20  import java.lang.reflect.Method;
21  import java.util.Iterator;
22  import java.util.List;
23  
24  import org.apache.commons.lang.ClassUtils;
25  
26  /**
27   * <p>Abstract superclass for type-safe enums with integer values suitable
28   * for use in <code>switch</code> statements.</p>
29   *
30   * <p><em>NOTE:</em>Due to the way in which Java ClassLoaders work, comparing
31   * <code>Enum</code> objects should always be done using the equals() method,
32   * not <code>==</code>. The equals() method will try <code>==</code> first so
33   * in most cases the effect is the same.</p>
34   *
35   * <p>To use this class, it must be subclassed. For example:</p>
36   *
37   * <pre>
38   * public final class JavaVersionEnum extends ValuedEnum {
39   *   //standard enums for version of JVM
40   *   public static final int  JAVA1_0_VALUE  = 100;
41   *   public static final int  JAVA1_1_VALUE  = 110;
42   *   public static final int  JAVA1_2_VALUE  = 120;
43   *   public static final int  JAVA1_3_VALUE  = 130;
44   *   public static final JavaVersionEnum  JAVA1_0  = new JavaVersionEnum( "Java 1.0", JAVA1_0_VALUE );
45   *   public static final JavaVersionEnum  JAVA1_1  = new JavaVersionEnum( "Java 1.1", JAVA1_1_VALUE );
46   *   public static final JavaVersionEnum  JAVA1_2  = new JavaVersionEnum( "Java 1.2", JAVA1_2_VALUE );
47   *   public static final JavaVersionEnum  JAVA1_3  = new JavaVersionEnum( "Java 1.3", JAVA1_3_VALUE );
48   *
49   *   private JavaVersionEnum(String name, int value) {
50   *     super( name, value );
51   *   }
52   * 
53   *   public static JavaVersionEnum getEnum(String javaVersion) {
54   *     return (JavaVersionEnum) getEnum(JavaVersionEnum.class, javaVersion);
55   *   }
56   * 
57   *   public static JavaVersionEnum getEnum(int javaVersion) {
58   *     return (JavaVersionEnum) getEnum(JavaVersionEnum.class, javaVersion);
59   *   }
60   * 
61   *   public static Map getEnumMap() {
62   *     return getEnumMap(JavaVersionEnum.class);
63   *   }
64   * 
65   *   public static List getEnumList() {
66   *     return getEnumList(JavaVersionEnum.class);
67   *   }
68   * 
69   *   public static Iterator iterator() {
70   *     return iterator(JavaVersionEnum.class);
71   *   }
72   * }
73   * </pre>
74   *
75   * <p><em>NOTE:</em>These are declared <code>final</code>, so compilers may 
76   * inline the code. Ensure you recompile everything when using final. </p>
77   *
78   * <p>The above class could then be used as follows:</p>
79   *
80   * <pre>
81   * public void doSomething(JavaVersionEnum ver) {
82   *   switch (ver.getValue()) {
83   *     case JAVA1_0_VALUE:
84   *       // ...
85   *       break;
86   *     case JAVA1_1_VALUE:
87   *       // ...
88   *       break;
89   *     //...
90   *   }
91   * }
92   * </pre>
93   *
94   * <p>As shown, each enum has a name and a value. These can be accessed using
95   * <code>getName</code> and <code>getValue</code>.</p>
96   *
97   * <p><em>NOTE:</em> Because the switch is ultimately sitting on top of an 
98   * int, the example above is not type-safe. That is, there is nothing that 
99   * checks that JAVA1_0_VALUE is a legal constant for JavaVersionEnum. </p>
100  *
101  * <p>The <code>getEnum</code> and <code>iterator</code> methods are recommended.
102  * Unfortunately, Java restrictions require these to be coded as shown in each subclass.
103  * An alternative choice is to use the {@link EnumUtils} class.</p>
104  *
105  * @author Apache Avalon project
106  * @author Stephen Colebourne
107  * @since 2.1 (class existed in enum package from v1.0)
108  * @version $Id: ValuedEnum.java 466275 2006-10-20 22:02:34Z bayard $
109  */
110 public abstract class ValuedEnum extends Enum {
111     
112     /**
113      * Required for serialization support.
114      * 
115      * @see java.io.Serializable
116      */
117     private static final long serialVersionUID = -7129650521543789085L;
118     
119     /**
120      * The value contained in enum.
121      */
122     private final int iValue;
123 
124     /**
125      * Constructor for enum item.
126      *
127      * @param name  the name of enum item
128      * @param value  the value of enum item
129      */
130     protected ValuedEnum(String name, int value) {
131         super(name);
132         iValue = value;
133     }
134 
135     /**
136      * <p>Gets an <code>Enum</code> object by class and value.</p>
137      *
138      * <p>This method loops through the list of <code>Enum</code>,
139      * thus if there are many <code>Enum</code>s this will be
140      * slow.</p>
141      * 
142      * @param enumClass  the class of the <code>Enum</code> to get
143      * @param value  the value of the <code>Enum</code> to get
144      * @return the enum object, or null if the enum does not exist
145      * @throws IllegalArgumentException if the enum class is <code>null</code>
146      */
147     protected static Enum getEnum(Class enumClass, int value) {
148         if (enumClass == null) {
149             throw new IllegalArgumentException("The Enum Class must not be null");
150         }
151         List list = Enum.getEnumList(enumClass);
152         for (Iterator it = list.iterator(); it.hasNext();) {
153             ValuedEnum enumeration = (ValuedEnum) it.next();
154             if (enumeration.getValue() == value) {
155                 return enumeration;
156             }
157         }
158         return null;
159     }
160 
161     /**
162      * <p>Get value of enum item.</p>
163      *
164      * @return the enum item's value.
165      */
166     public final int getValue() {
167         return iValue;
168     }
169 
170     /**
171      * <p>Tests for order.</p>
172      *
173      * <p>The default ordering is numeric by value, but this
174      * can be overridden by subclasses.</p>
175      *
176      * <p>NOTE: From v2.2 the enums must be of the same type.
177      * If the parameter is in a different class loader than this instance,
178      * reflection is used to compare the values.</p>
179      *
180      * @see java.lang.Comparable#compareTo(Object)
181      * @param other  the other object to compare to
182      * @return -ve if this is less than the other object, +ve if greater than,
183      *  <code>0</code> of equal
184      * @throws ClassCastException if other is not an <code>Enum</code>
185      * @throws NullPointerException if other is <code>null</code>
186      */
187     public int compareTo(Object other) {
188         if (other == this) {
189             return 0;
190         }
191         if (other.getClass() != this.getClass()) {
192             if (other.getClass().getName().equals(this.getClass().getName())) {
193                 return iValue - getValueInOtherClassLoader(other);
194             }
195             throw new ClassCastException(
196                     "Different enum class '" + ClassUtils.getShortClassName(other.getClass()) + "'");
197         }
198         return iValue - ((ValuedEnum) other).iValue;
199     }
200 
201     /**
202      * <p>Use reflection to return an objects value.</p>
203      *
204      * @param other  the object to determine the value for
205      * @return the value
206      */
207     private int getValueInOtherClassLoader(Object other) {
208         try {
209             Method mth = other.getClass().getMethod("getValue", null);
210             Integer value = (Integer) mth.invoke(other, null);
211             return value.intValue();
212         } catch (NoSuchMethodException e) {
213             // ignore - should never happen
214         } catch (IllegalAccessException e) {
215             // ignore - should never happen
216         } catch (InvocationTargetException e) {
217             // ignore - should never happen
218         }
219         throw new IllegalStateException("This should not happen");
220     }
221 
222     /**
223      * <p>Human readable description of this <code>Enum</code> item.</p>
224      *
225      * @return String in the form <code>type[name=value]</code>, for example:
226      *  <code>JavaVersion[Java 1.0=100]</code>. Note that the package name is
227      *  stripped from the type name.
228      */
229     public String toString() {
230         if (iToString == null) {
231             String shortName = ClassUtils.getShortClassName(getEnumClass());
232             iToString = shortName + "[" + getName() + "=" + getValue() + "]";
233         }
234         return iToString;
235     }
236 }