Java Reflection Super Class getSuperclassesForHeight(Collection> classes, int height)

Here you can find the source of getSuperclassesForHeight(Collection> classes, int height)

Description

Returns the list of super-classes of the specified height for the given collection of classes.

License

Apache License

Declaration

private static List<Class<?>> getSuperclassesForHeight(Collection<Class<?>> classes, int height) 

Method Source Code


//package com.java2s;
/*/*from   w w  w  .j  a va  2s .c o  m*/
 * Copyright 2013 Anton Karmanov
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *     http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

public class Main {
    /**
     * Returns the list of super-classes of the specified height for the given collection of classes.
     */
    private static List<Class<?>> getSuperclassesForHeight(Collection<Class<?>> classes, int height) {
        List<Class<?>> superClasses = new ArrayList<>();
        for (Class<?> cls : classes) {
            Class<?> supCls = getSuperclassForHeight(cls, height);
            superClasses.add(supCls);
        }
        return superClasses;
    }

    /**
     * For the given class, returns its superclass which has the specified height. The height must be
     * equal or less than the class' height.
     */
    private static Class<?> getSuperclassForHeight(Class<?> cls, int height) {
        int clsHeight = getClassHierarchyHeight(cls);
        int delta = clsHeight - height;
        Class<?> superCls = cls;
        for (int i = 0; i < delta; ++i) {
            superCls = superCls.getSuperclass();
        }
        return superCls;
    }

    /**
     * Returns the class' height.
     */
    private static int getClassHierarchyHeight(final Class<?> cls) {
        int result = 0;
        Class<?> curCls = cls;
        while (curCls != null) {
            ++result;
            curCls = curCls.getSuperclass();
        }
        return result;
    }
}

Related

  1. getSuperclasses(Class clazz)
  2. getSuperClasses(Class cls)
  3. getSuperClasses(Class entryClass)
  4. getSuperclasses(Class the_class)
  5. getSuperClasses(final Class clazz)
  6. getSuperClasss(Class sourceClass, boolean isAddCurrentClass)
  7. hasSuperclass(Class klass, Class ancestor)
  8. resolveAllSuperclasses(Class type)