forked from kohsuke/com4j
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathEnumDictionary.java
More file actions
107 lines (88 loc) · 2.71 KB
/
Copy pathEnumDictionary.java
File metadata and controls
107 lines (88 loc) · 2.71 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
package com4j;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.WeakHashMap;
/**
* Provides faster number <-> enum conversion.
*
* @author Kohsuke Kawaguchi (kk@kohsuke.org)
*/
abstract class EnumDictionary<T extends Enum<T>> {
protected final Class<T> clazz;
private EnumDictionary(Class<T> clazz) {
this.clazz = clazz;
assert clazz.isEnum();
}
/**
* Looks up a dictionary from an enum class.
*/
public static <T extends Enum<T>>
EnumDictionary<T> get( Class<T> clazz ) {
EnumDictionary<T> dic = registry.get(clazz);
if(dic==null) {
boolean sparse = ComEnum.class.isAssignableFrom(clazz);
if(sparse)
dic = new Sparse<T>(clazz);
else
dic = new Continuous<T>(clazz);
registry.put(clazz,dic);
}
return dic;
}
/**
* Convenience method to be invoked by JNI.
*/
static <T extends Enum<T>>
T get( Class<T> clazz, int v ) {
return get(clazz).constant(v);
}
/**
* Gets the integer value for the given enum constant.
*/
abstract int value( Enum<T> t );
/**
* Gets the enum constant object from its integer value.
*/
abstract T constant( int v );
/**
* For enum constants that doesn't use any {@link ComEnum}.
*/
static class Continuous<T extends Enum<T>> extends EnumDictionary<T> {
private T[] consts;
private Continuous(Class<T> clazz) {
super(clazz);
consts = clazz.getEnumConstants();
}
public int value(Enum<T> t ) {
return t.ordinal();
}
public T constant( int v ) {
return consts[v];
}
}
/**
* For enum constants with {@link ComEnum}.
*/
static class Sparse<T extends Enum<T>> extends EnumDictionary<T> {
private final Map<Integer,T> fromValue = new HashMap<Integer,T>();
private Sparse(Class<T> clazz) {
super(clazz);
T[] consts = clazz.getEnumConstants();
for( T v : consts ) {
fromValue.put(((ComEnum)v).comEnumValue(),v);
}
}
public int value(Enum<T> t ) {
return ((ComEnum)t).comEnumValue();
}
public T constant( int v ) {
T t = fromValue.get(v);
if(t==null)
throw new IllegalArgumentException(clazz.getName()+" has no constant of the value "+v);
return t;
}
}
private static final Map<Class<? extends Enum>,EnumDictionary> registry =
Collections.synchronizedMap(new WeakHashMap<Class<? extends Enum>,EnumDictionary>());
}