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.ArrayList;
19  import java.util.Iterator;
20  import java.util.List;
21  
22  /**
23   * An inheritence sequence. The target class is first, 
24   * followed by its superclass and its interfaces. Then the 
25   * lookup recurses through the superclass and interfaces 
26   * with the same strategy. 
27   * It is ensured that java.lang.Object is last in the sequence.
28   */
29  public class BasicInheritor implements Inheritor {
30  
31      private Class clazz;
32      
33      public BasicInheritor() {
34      }
35      
36      public BasicInheritor(Class clazz) {
37          setTarget(clazz);
38      }
39      
40      public void setTarget(Class clazz) {
41          this.clazz = clazz;
42      }
43      
44      public Class getTarget() {
45          return clazz;
46      }
47      
48      public Iterator iterator() {
49          List list = new ArrayList();
50  
51          addToList(list, clazz);
52          addClassParents(list, clazz);
53  
54          list.add( Object.class );
55  
56          return list.iterator();
57      }
58      
59      private void addClassParents(List list, Class clazz) {
60          if (clazz == null) {
61              return;
62          }
63  
64          Class superclass = clazz.getSuperclass();
65          addToList(list, superclass);
66  
67          Class[] interfaces = clazz.getInterfaces();
68          for (int i = 0; i < interfaces.length; i++) {
69              addToList(list, interfaces[i]);
70          }
71  
72          for (int i = 0; i < interfaces.length; i++) {
73              addClassParents(list, interfaces[i]);
74          }
75  
76          addClassParents(list, superclass);
77      }
78      
79      private void addToList(List list, Class clazz) {
80          if( clazz == null ) {
81              return;
82          }
83  
84          if( Object.class == clazz ) {
85              return;
86          }
87  
88          if( list.contains( clazz ) ) {
89              return;
90          }
91  
92          list.add(clazz);
93      }
94      
95  }