01: /**
02: * $RCSfile$
03: * $Revision: 42 $
04: * $Date: 2004-10-21 00:28:12 -0700 (Thu, 21 Oct 2004) $
05: *
06: * Copyright (C) 2004 Jive Software. All rights reserved.
07: *
08: * This software is published under the terms of the GNU Public License (GPL),
09: * a copy of which is included in this distribution.
10: */package org.jivesoftware.util;
11:
12: import java.util.*;
13:
14: /**
15: * <p>A type safe enumeration object that is keyed by an Int
16: * value for switch statements and storage in DBs.</p>
17: * <p/>
18: * <p>Used for indicating distinct states in a generic manner
19: * where each enum should have an associated int value. The
20: * given int should be unique for each enum value as hashCode
21: * and equals depends solely on the int value given. Most
22: * child classes should extend IntEnum and create static instances.</p>
23: *
24: * @author Iain Shigeoka
25: */
26: public class IntEnum extends Enum {
27:
28: private int value;
29: protected static Hashtable enumTypes = new Hashtable();
30:
31: protected IntEnum(String name, int val) {
32: super (name);
33: this .value = val;
34: }
35:
36: /**
37: * Returns the int value associated with the enum.
38: *
39: * @return the int value of the enum.
40: */
41: public int getValue() {
42: return value;
43: }
44:
45: public boolean equals(Object object) {
46: if (this == object) {
47: return true;
48: } else if ((this .getClass().isInstance(object))
49: && value == (((IntEnum) object).value)) {
50: return true;
51: } else {
52: return false;
53: }
54: }
55:
56: /**
57: * <p>Checks in an enum for use in the getEnumFromInt() method.</p>
58: *
59: * @param enumeration The enum to be registered
60: */
61: protected static void register(IntEnum enumeration) {
62: Map enums = (Map) enumTypes.get(enumeration.getClass());
63: if (enums == null) {
64: enums = new HashMap<Integer, Object>();
65: enumTypes.put(enumeration.getClass(), enums);
66: }
67: enums.put(enumeration.getValue(), enumeration);
68: }
69:
70: /**
71: * <p>Obtain the enum associated with the given value.</p>
72: * <p>Values must be registered earlier using the register() method.</p>
73: *
74: * @param value the value to lookup the enum for
75: * @return The associated enum or null if no matching enum exists
76: */
77: protected static IntEnum getEnumFromInt(Class enumClass, int value) {
78: Map enums = (Map) enumTypes.get(enumClass);
79: if (enums != null) {
80: return (IntEnum) enums.get(value);
81: }
82: return null;
83: }
84:
85: public int hashCode() {
86: return value;
87: }
88:
89: public String toString() {
90: return Integer.toString(value) + " " + super.toString();
91: }
92: }
|