View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one or more
3    * contributor license agreements.  See the NOTICE file distributed with
4    * this work for additional information regarding copyright ownership.
5    * The ASF licenses this file to You under the Apache License, Version 2.0
6    * (the "License"); you may not use this file except in compliance with
7    * the License.  You may obtain a copy of the License at
8    *
9    *      http://www.apache.org/licenses/LICENSE-2.0
10   *
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the License for the specific language governing permissions and
15   * limitations under the License.
16   */
17  package org.apache.commons.lang3.reflect;
18  
19  import org.apache.commons.lang3.BooleanUtils;
20  
21  /**
22   * <p>Utility methods focusing on inheritance.</p>
23   *
24   * @since 3.2
25   */
26  public class InheritanceUtils {
27  
28      /**
29       * <p>{@link InheritanceUtils} instances should NOT be constructed in standard programming.
30       * Instead, the class should be used as
31       * {@code MethodUtils.getAccessibleMethod(method)}.</p>
32       *
33       * <p>This constructor is {@code public} to permit tools that require a JavaBean
34       * instance to operate.</p>
35       */
36      public InheritanceUtils() {
37          super();
38      }
39  
40      /**
41       * <p>Returns the number of inheritance hops between two classes.</p>
42       *
43       * @param child the child class, may be {@code null}
44       * @param parent the parent class, may be {@code null}
45       * @return the number of generations between the child and parent; 0 if the same class;
46       * -1 if the classes are not related as child and parent (includes where either class is null)
47       * @since 3.2
48       */
49      public static int distance(final Class<?> child, final Class<?> parent) {
50          if (child == null || parent == null) {
51              return -1;
52          }
53  
54          if (child.equals(parent)) {
55              return 0;
56          }
57  
58          final Class<?> cParent = child.getSuperclass();
59          int d = BooleanUtils.toInteger(parent.equals(cParent));
60  
61          if (d == 1) {
62              return d;
63          } else {
64              d += distance(cParent, parent);
65              return d > 0 ? d + 1 : -1;
66          }
67      }
68  }