01: /*
02: * Copyright 2006 Ethan Nicholas. All rights reserved.
03: * Use is subject to license terms.
04: */
05: package jaxx;
06:
07: import jaxx.reflect.*;
08:
09: import java.util.*;
10:
11: /** A Map implementation which uses Classes as keys. <code>ClassMap</code> differs from typical maps
12: * in that it takes subclasses into account; mapping a class to a value also maps all subclasses of
13: * that class to the value.
14: * <p>
15: * A <code>get</code> operation will return the value associated with the class itself, or failing
16: * that, with its nearest ancestor for which there exists a mapping.
17: */
18: public class ClassMap extends HashMap {
19: /** Keeps track of automatically-added Classes so we can distinguish them from user-added
20: * Classes. Unknown Classes are automatically added to the map during <code>get</code>
21: * calls to speed up subsequent requests, but they must be updated when the mappings
22: * for their superclasses are modified.
23: */
24: private List/*<ClassDescriptor>*/autoKeys = new ArrayList/*<ClassDescriptor>*/();
25:
26: /** Returns the value associated with the key <code>Class</code>. If the class itself does not have
27: * a mapping, its superclass will be checked, and so on until an ancestor class with a mapping is
28: * located. If none of the class' ancestors have a mapping, <code>null</code> is returned.
29: *
30: *@param key the class to check
31: *@return the mapping for the class
32: */
33: public Object get(Object key) {
34: Object result = null;
35: ClassDescriptor c = (ClassDescriptor) key;
36: while (c != null) {
37: result = super .get(c);
38: if (result != null)
39: break;
40: c = c.getSuperclass();
41: }
42:
43: if (result == null && ((ClassDescriptor) key).isInterface()) {
44: result = get(ClassDescriptorLoader
45: .getClassDescriptor(Object.class));
46: }
47:
48: if (c != key && result != null) { // no mapping for the class itself, but found one for a superclass
49: put(key, result);
50: autoKeys.add(key);
51: }
52: return result;
53: }
54:
55: /** Associates a value with a class and all of its descendents.
56: *
57: *@param key the class to map
58: *@param value the value to map to the class
59: *@return the old value associated with the class
60: */
61: public Object put(Object key, Object value) {
62: if (!(key instanceof ClassDescriptor))
63: throw new IllegalArgumentException(
64: "expected ClassDescriptor, got " + key);
65: if (autoKeys.size() > 0) { // remove all automatic keys which descend from the class being modified
66: ClassDescriptor c = (ClassDescriptor) key;
67: Iterator/*<Class>*/i = autoKeys.iterator();
68: while (i.hasNext()) {
69: ClassDescriptor auto = (ClassDescriptor) i.next();
70: if (c.isAssignableFrom(auto)) {
71: i.remove();
72: remove(auto);
73: }
74: }
75: }
76: return super.put(key, value);
77: }
78: }
|