001/* 002 * Licensed to the Apache Software Foundation (ASF) under one or more 003 * contributor license agreements. See the NOTICE file distributed with 004 * this work for additional information regarding copyright ownership. 005 * The ASF licenses this file to You under the Apache License, Version 2.0 006 * (the "License"); you may not use this file except in compliance with 007 * the License. You may obtain a copy of the License at 008 * 009 * https://www.apache.org/licenses/LICENSE-2.0 010 * 011 * Unless required by applicable law or agreed to in writing, software 012 * distributed under the License is distributed on an "AS IS" BASIS, 013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 014 * See the License for the specific language governing permissions and 015 * limitations under the License. 016 */ 017package org.apache.commons.lang3.reflect; 018 019import org.apache.commons.lang3.BooleanUtils; 020 021/** 022 * Utility methods focusing on inheritance. 023 * 024 * @since 3.2 025 */ 026public class InheritanceUtils { 027 028 /** 029 * Returns the number of inheritance hops between two classes. 030 * 031 * @param child the child class, may be {@code null} 032 * @param parent the parent class, may be {@code null} 033 * @return the number of generations between the child and parent; 0 if the same class; 034 * -1 if the classes are not related as child and parent (includes where either class is null) 035 * @since 3.2 036 */ 037 public static int distance(final Class<?> child, final Class<?> parent) { 038 if (child == null || parent == null) { 039 return -1; 040 } 041 if (child.equals(parent)) { 042 return 0; 043 } 044 final Class<?> cParent = child.getSuperclass(); 045 int d = BooleanUtils.toInteger(parent.equals(cParent)); 046 if (d == 1) { 047 return d; 048 } 049 d += distance(cParent, parent); 050 return d > 0 ? d + 1 : -1; 051 } 052 053 /** 054 * {@link InheritanceUtils} instances should NOT be constructed in standard programming. 055 * Instead, the class should be used as 056 * {@code MethodUtils.getAccessibleMethod(method)}. 057 * 058 * <p>This constructor is {@code public} to permit tools that require a JavaBean 059 * instance to operate.</p> 060 * 061 * @deprecated TODO Make private in 4.0. 062 */ 063 @Deprecated 064 public InheritanceUtils() { 065 // empty 066 } 067}