Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
//License from project: Apache License 

import java.lang.reflect.Type;

public class Main {
    /**
     * Searches for ofClass in the inherited classes and interfaces of inClass. If ofClass has been found in the super
     * classes/interfaces of inClass, then the generic type corresponding to inClass and its TypeVariables is returned,
     * otherwise null. For example :
     * 
     * <pre>
     * abstract class MyClass implements Serializer&lt;Number&gt; {
     * 
     * }
     * 
     * // type value will be the parameterized type Serializer&lt;Number&gt;
     * Type type = lookupGenericType(Serializer.class, MyClass.class);
     * </pre>
     */
    public final static Type lookupGenericType(Class<?> ofClass, Class<?> inClass) {
        if (ofClass == null || inClass == null || !ofClass.isAssignableFrom(inClass))
            return null;
        if (ofClass.equals(inClass))
            return inClass;

        if (ofClass.isInterface()) {
            // lets look if the interface is directly implemented by fromClass
            Class<?>[] interfaces = inClass.getInterfaces();

            for (int i = 0; i < interfaces.length; i++) {
                // do they match?
                if (ofClass.equals(interfaces[i])) {
                    return inClass.getGenericInterfaces()[i];
                } else {
                    Type superType = lookupGenericType(ofClass, interfaces[i]);
                    if (superType != null)
                        return superType;
                }
            }
        }

        // ok it's not one of the directly implemented interfaces, lets try extended class
        Class<?> superClass = inClass.getSuperclass();
        if (ofClass.equals(superClass))
            return inClass.getGenericSuperclass();
        return lookupGenericType(ofClass, inClass.getSuperclass());
    }
}