litesoft
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
|
package com.temp.shared.utils;
import java.util.HashMap;
import java.util.Map;
public class Global {
@SuppressWarnings("rawtypes")
private static final Map INSTANCES_BY_CLASS = new HashMap();
/**
* Get the required instance associated with the klass.
*
* @param klass
* !null
*
* @throws IllegalStateException
* if there is currently nothing associated with the klass
*
* @return !null instance associated with the klass
*/
public static <T> T get(Class<T> klass) throws IllegalStateException {
T instance = getOptional(klass);
if (instance != null) {
return instance;
}
throw new IllegalStateException("No 'instance' associated with class: " + klass);
}
/**
* Set/Replace/Clear the current instance associated with a class
*
* @param klass
* !null
* @param instance
* if null then removes current instance associated with the
* class, if !null then sets / replaces the current instance
* associated with the class.
*
* @return the previous instance associated with klass.
*/
public static <T> T set(Class<T> klass, T instance) {
Assert.notNull("Class", klass);
synchronized (INSTANCES_BY_CLASS) {
if (instance == null) {
return ObjectUtils.cast(INSTANCES_BY_CLASS.remove(klass));
} else {
return ObjectUtils.cast(put(klass, instance));
}
}
}
/**
* Get the optional instance associated with the klass.
*
* @param klass
* !null
*
* @return instance associated with the klass or null
*/
public static <T> T getOptional(Class<T> klass) {
Assert.notNull("Class", klass);
synchronized (INSTANCES_BY_CLASS) {
return ObjectUtils.cast(INSTANCES_BY_CLASS.get(klass));
}
}
@SuppressWarnings("unchecked")
private static Object put(Object key, Object value) {
return INSTANCES_BY_CLASS.put(key, value);
}
}
|
Revision |
Author |
Commited |
Message |
626
|
GeorgeS
|
Wed 11 Apr, 2012 19:39:41 +0000 |
|