View Javadoc

1   /*
2    *  Copyright 2003-2004 The Apache Software Foundation
3    *
4    *  Licensed under the Apache License, Version 2.0 (the "License");
5    *  you may not use this file except in compliance with the License.
6    *  You may obtain a copy of the License at
7    *
8    *      http://www.apache.org/licenses/LICENSE-2.0
9    *
10   *  Unless required by applicable law or agreed to in writing, software
11   *  distributed under the License is distributed on an "AS IS" BASIS,
12   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   *  See the License for the specific language governing permissions and
14   *  limitations under the License.
15   */
16  package org.apache.commons.convert1.util;
17  
18  import java.util.HashMap;
19  import java.util.Iterator;
20  
21  /**
22   * A map which stores objects by a key Class.
23   * When obtaining the object, it will check inheritence and 
24   * interface trees to see if the Class matches.
25   */
26  public class ClassMap extends ProxyMap {
27  
28      private Inheritor inh;
29      
30      public ClassMap() {
31          this(new BasicInheritor());
32      }
33      
34      public ClassMap(Inheritor inh) {
35          super(new HashMap());
36          this.inh = inh;
37      }
38      
39      public Inheritor getInheritor() {
40          return inh;
41      }
42      
43      /**
44       * Get the object from the map. If the key is not 
45       * a Class object, then it uses the Class of the object.
46       */
47      public Object get(Object key) {
48          if(key == null) {
49              return null;
50          }
51          Class clss = null;
52  
53          if(key instanceof Class) {
54              clss = (Class) key;
55          } else {
56              clss = key.getClass();
57          }
58  
59          Object obj = super.get(clss);
60  
61          if(obj == null) {
62  
63              inh.setTarget(clss);
64              Iterator itr = inh.iterator();
65              while(itr.hasNext() && obj == null) {
66                  obj = super.get(itr.next());
67              }
68          }
69  
70          return obj;
71      }
72  
73  }