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     * 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
042        if (child.equals(parent)) {
043            return 0;
044        }
045
046        final Class<?> cParent = child.getSuperclass();
047        int d = BooleanUtils.toInteger(parent.equals(cParent));
048
049        if (d == 1) {
050            return d;
051        }
052        d += distance(cParent, parent);
053        return d > 0 ? d + 1 : -1;
054    }
055
056    /**
057     * {@link InheritanceUtils} instances should NOT be constructed in standard programming.
058     * Instead, the class should be used as
059     * {@code MethodUtils.getAccessibleMethod(method)}.
060     *
061     * <p>This constructor is {@code public} to permit tools that require a JavaBean
062     * instance to operate.</p>
063     */
064    public InheritanceUtils() {
065    }
066}