1 package org.itracker.model;
2
3 /**
4 * An interface to be implemented by java.lang.Enum classes that need
5 * to associate a unique and constant integer code to their enum constants.
6 * <p/>
7 * <p>The main use case is to allow to persist an enum constant to
8 * an integer rather than a string value, which is supported directly
9 * by the java.lang.Enum class through the enum.name() and enum.valueOf(String)
10 * methods. <br>
11 * The enum.ordinal() position could be used, but isn't the best approach for
12 * this use case because we don't have any control on it :
13 * it is zero-based and changes if the position of the enum constant changes.
14 * <br>
15 * Using the enum name isn't satisfactory either because we would have
16 * to update the database if we ever need to rename an enum constant. </p>
17 * <p/>
18 * <p>This class allows to migrate to Java 5 enums retaining full backwards
19 * compatibility with iTracker 2, in which all enumerations were simply defined
20 * as <code>static final int</code> fields. </p>
21 * <p/>
22 * <p>This interface allows to handle all such enums consistently
23 * and to use a single Hibernate custom type to persist them all. </p>
24 *
25 * @author johnny
26 */
27 public interface IntCodeEnum<E extends Enum<E>> {
28
29 int DEFAULT_CODE = 1;
30
31 /**
32 * Returns the integer value representing this enum constant.
33 *
34 * @return unique constant as defined in iTracker 2
35 */
36 Integer getCode();
37
38 /**
39 * Returns a java.lang.Enum constant matching the given integer value.
40 * <p/>
41 * <p>This method should actually be static, so that we don't need
42 * an enum constant instance to lookup another instance by code.
43 * <br>
44 * However Java interfaces don't allow static methods and Java 5 enums
45 * must inherit java.lang.Enum directly. So there's no way to create
46 * a common base class with a static fromCode(int) method
47 * for all enums in our application for EnumCodeUserType to use
48 * in a type-safe way! </p>
49 *
50 * <p>You should instead implement a static valueOf(int) wrapped by this method:
51 * <pre>
52 * static final E valueOf(Integer code) {
53 * for (E val: values()) {
54 * if (val.code == code) {
55 * return val;
56 * }
57 * }
58 * throw new IllegalArgumentException("Unknown code : " + code);
59 * }
60 *
61 * </pre>
62 * </p>
63 *
64 * @param code unique enum constant as defined in iTracker 2
65 * @return java.lang.Enum constant instance for the given code
66 * @throws IllegalArgumentException no matching enum constant for
67 * the given <code>code</code>
68 */
69 E fromCode(Integer code);
70
71 }