| 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 | * Utility methods focusing on inheritance. |
| 23 | * |
| 24 | * @since 3.2 |
| 25 | */ |
| 26 | public class InheritanceUtils { |
| 27 | |
| 28 | /** |
| 29 | * Returns the number of inheritance hops between two classes. |
| 30 | * |
| 31 | * @param child the child class, may be {@code null} |
| 32 | * @param parent the parent class, may be {@code null} |
| 33 | * @return the number of generations between the child and parent; 0 if the same class; |
| 34 | * -1 if the classes are not related as child and parent (includes where either class is null) |
| 35 | * @since 3.2 |
| 36 | */ |
| 37 | public static int distance(final Class<?> child, final Class<?> parent) { |
| 38 | if (child == null || parent == null) { |
| 39 | return -1; |
| 40 | } |
| 41 | |
| 42 | if (child.equals(parent)) { |
| 43 | return 0; |
| 44 | } |
| 45 | |
| 46 | final Class<?> cParent = child.getSuperclass(); |
| 47 | int d = BooleanUtils.toInteger(parent.equals(cParent)); |
| 48 | |
| 49 | if (d == 1) { |
| 50 | return d; |
| 51 | } |
| 52 | d += distance(cParent, parent); |
| 53 | return d > 0 ? d + 1 : -1; |
| 54 | } |
| 55 | |
| 56 | /** |
| 57 | * {@link InheritanceUtils} instances should NOT be constructed in standard programming. |
| 58 | * Instead, the class should be used as |
| 59 | * {@code MethodUtils.getAccessibleMethod(method)}. |
| 60 | * |
| 61 | * <p>This constructor is {@code public} to permit tools that require a JavaBean |
| 62 | * instance to operate.</p> |
| 63 | * |
| 64 | * @deprecated TODO Make private in 4.0. |
| 65 | */ |
| 66 | @Deprecated |
| 67 | public InheritanceUtils() { |
| 68 | // empty |
| 69 | } |
| 70 | } |