    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 *      http://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     * {@link InheritanceUtils} instances should NOT be constructed in standard programming.
    030     * Instead, the class should be used as
    031     * {@code MethodUtils.getAccessibleMethod(method)}.
    032     *
    033     * <p>This constructor is {@code public} to permit tools that require a JavaBean
    034     * instance to operate.</p>
    035     */
    036    public InheritanceUtils() {
    037    }
    038
    039    /**
    040     * Returns the number of inheritance hops between two classes.
    041     *
    042     * @param child the child class, may be {@code null}
    043     * @param parent the parent class, may be {@code null}
    044     * @return the number of generations between the child and parent; 0 if the same class;
    045     * -1 if the classes are not related as child and parent (includes where either class is null)
    046     * @since 3.2
    047     */
    048    public static int distance(final Class<?> child, final Class<?> parent) {
    049        if (child == null || parent == null) {
    050            return -1;
    051        }
    052
    053        if (child.equals(parent)) {
    054            return 0;
    055        }
    056
    057        final Class<?> cParent = child.getSuperclass();
    058        int d = BooleanUtils.toInteger(parent.equals(cParent));
    059
    060        if (d == 1) {
    061            return d;
    062        }
    063        d += distance(cParent, parent);
    064        return d > 0 ? d + 1 : -1;
    065    }
    066}