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 * <p>Utility methods focusing on inheritance.</p>
023 *
024 * @since 3.2
025 */
026public class InheritanceUtils {
027
028    /**
029     * <p>{@link InheritanceUtils} instances should NOT be constructed in standard programming.
030     * Instead, the class should be used as
031     * {@code MethodUtils.getAccessibleMethod(method)}.</p>
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        super();
038    }
039
040    /**
041     * <p>Returns the number of inheritance hops between two classes.</p>
042     *
043     * @param child the child class, may be {@code null}
044     * @param parent the parent class, may be {@code null}
045     * @return the number of generations between the child and parent; 0 if the same class;
046     * -1 if the classes are not related as child and parent (includes where either class is null)
047     * @since 3.2
048     */
049    public static int distance(final Class<?> child, final Class<?> parent) {
050        if (child == null || parent == null) {
051            return -1;
052        }
053
054        if (child.equals(parent)) {
055            return 0;
056        }
057
058        final Class<?> cParent = child.getSuperclass();
059        int d = BooleanUtils.toInteger(parent.equals(cParent));
060
061        if (d == 1) {
062            return d;
063        }
064        d += distance(cParent, parent);
065        return d > 0 ? d + 1 : -1;
066    }
067}