Example usage for java.lang Class getGenericSuperclass

List of usage examples for java.lang Class getGenericSuperclass

Introduction

In this page you can find the example usage for java.lang Class getGenericSuperclass.

Prototype

public Type getGenericSuperclass() 

Source Link

Document

Returns the Type representing the direct superclass of the entity (class, interface, primitive type or void) represented by this Class .

Usage

From source file:net.jodah.typetools.TypeResolver.java

private static Map<TypeVariable<?>, Type> getTypeVariableMap(final Class<?> targetType,
        Class<?> functionalInterface) {
    Reference<Map<TypeVariable<?>, Type>> ref = typeVariableCache.get(targetType);
    Map<TypeVariable<?>, Type> map = ref != null ? ref.get() : null;

    if (map == null) {
        map = new HashMap<TypeVariable<?>, Type>();

        // Populate lambdas
        if (functionalInterface != null)
            populateLambdaArgs(functionalInterface, targetType, map);

        // Populate interfaces
        populateSuperTypeArgs(targetType.getGenericInterfaces(), map, functionalInterface != null);

        // Populate super classes and interfaces
        Type genericType = targetType.getGenericSuperclass();
        Class<?> type = targetType.getSuperclass();
        while (type != null && !Object.class.equals(type)) {
            if (genericType instanceof ParameterizedType)
                populateTypeArgs((ParameterizedType) genericType, map, false);
            populateSuperTypeArgs(type.getGenericInterfaces(), map, false);

            genericType = type.getGenericSuperclass();
            type = type.getSuperclass();
        }/*from   www. jav  a  2  s  . c  o  m*/

        // Populate enclosing classes
        type = targetType;
        while (type.isMemberClass()) {
            genericType = type.getGenericSuperclass();
            if (genericType instanceof ParameterizedType)
                populateTypeArgs((ParameterizedType) genericType, map, functionalInterface != null);

            type = type.getEnclosingClass();
        }

        if (CACHE_ENABLED)
            typeVariableCache.put(targetType, new WeakReference<Map<TypeVariable<?>, Type>>(map));
    }

    return map;
}

From source file:cn.nekocode.itempool.ItemPool.java

public void addType(@NonNull Class<? extends Item> itemClass) {
    ParameterizedType parameterizedType = (ParameterizedType) itemClass.getGenericSuperclass();
    Class dataClass = (Class) parameterizedType.getActualTypeArguments()[0];

    ItemType type = new ItemType(itemClass);
    mapOfType.put(dataClass, type);/*from  w  w w. j  a  v a  2  s. co m*/
    mapOfItemClass.put(type.TYPE_ID, itemClass);
}

From source file:org.jboss.windup.reporting.transformers.MetaResultTransformResolver.java

private void instantiateMapper(String className)
        throws ClassNotFoundException, InstantiationException, IllegalAccessException {
    Class clz = Class.forName(className);
    MetaResultTransformer transformer = (MetaResultTransformer) clz.newInstance();
    String key = (((ParameterizedType) clz.getGenericSuperclass()).getActualTypeArguments()[0]).toString();
    transformResolver.put(key, transformer);
}

From source file:com.hrules.darealmvp.DRDialogFragmentV4.java

@SuppressWarnings("unchecked")
private P internalGetPresenter()
        throws java.lang.InstantiationException, IllegalAccessException, ClassNotFoundException {
    Class clazz = getClass();
    Type genericSuperclass;//  ww w  .ja  v a2  s . c  om
    for (;;) {
        genericSuperclass = clazz.getGenericSuperclass();
        if (genericSuperclass instanceof ParameterizedType) {
            break;
        }
        clazz = clazz.getSuperclass();
    }
    Type presenterClass = ((ParameterizedType) genericSuperclass).getActualTypeArguments()[0];
    return (P) Class.forName(presenterClass.toString().split(" ")[1]).newInstance();
}

From source file:nl.luminis.test.util.annotations.HierarchyDiscovery.java

private void discoverFromClass(Class<?> clazz) {
    discoverTypes(resolveType(type, type, clazz.getGenericSuperclass()));
    for (Type c : clazz.getGenericInterfaces()) {
        discoverTypes(resolveType(type, type, c));
    }/*  w w w  .  j  a va2 s. c o m*/
}

From source file:ca.uhn.fhir.context.RuntimePrimitiveDatatypeDefinition.java

private void determineNativeType(Class<? extends IPrimitiveType<?>> theImplementingClass) {
    Class<?> clazz = theImplementingClass;
    while (clazz.equals(Object.class) == false) {
        Type type = clazz.getGenericSuperclass();
        if (type instanceof ParameterizedType) {
            ParameterizedType superPt = (ParameterizedType) type;
            Type rawType = superPt.getRawType();
            if (rawType instanceof Class) {
                Class<?> rawClass = (Class<?>) rawType;
                if (rawClass.getName().endsWith(".BasePrimitive")
                        || rawClass.getName().endsWith(".PrimitiveType")) {
                    Type typeVariable = superPt.getActualTypeArguments()[0];
                    if (typeVariable instanceof Class) {
                        myNativeType = (Class<?>) typeVariable;
                        break;
                    }/*from  w w w  .  j  a va 2 s. c  o  m*/
                }
            }
        }
        clazz = clazz.getSuperclass();
    }
}

From source file:org.openmainframe.ade.impl.PropertyAnnotation.java

/**
 * Find out what are the concrete classes used in an offspring class for the generic placeholders of a base class/interface
 * //from w  w  w . j a v  a  2  s  . c  om
 * @param <T> base class type
 * @param offspring class or interface subclassing or extending the base class
 * @param base class with generic arguments
 * @param actualArgs the actual type arguments passed to the offspring class (omit unless useful)
 * @return actual generic type arguments, must match the type parameters of the offspring class. If omitted, the
 * type parameters will be used instead.
 */
@SuppressWarnings("unchecked")
public static <T> Type[] resolveActualTypeArgs(Class<? extends T> offspring, Class<T> base,
        Type... actualArgs) {

    //  If actual types are omitted, the type parameters will be used instead.
    if (actualArgs.length == 0) {
        actualArgs = offspring.getTypeParameters();
    }
    // map generic parameters into the actual types
    final Map<String, Type> genericVariables = new TreeMap<String, Type>();
    for (int i = 0; i < actualArgs.length; i++) {
        final TypeVariable<?> typeVariable = (TypeVariable<?>) offspring.getTypeParameters()[i];
        genericVariables.put(typeVariable.getName(), actualArgs[i]);
    }

    // Find direct ancestors (superclass, interfaces)
    final List<Type> ancestors = new LinkedList<Type>();
    if (offspring.getGenericSuperclass() != null) {
        ancestors.add(offspring.getGenericSuperclass());
    }
    for (Type t : offspring.getGenericInterfaces()) {
        ancestors.add(t);
    }

    // Recurse into ancestors (superclass, interfaces)
    for (Type type : ancestors) {
        if (type instanceof Class<?>) {
            // ancestor is non-parameterized. Recurse only if it matches the base class.
            final Class<?> ancestorClass = (Class<?>) type;
            if (base.isAssignableFrom(ancestorClass)) {
                final Type[] result = resolveActualTypeArgs((Class<? extends T>) ancestorClass, base);
                if (result != null) {
                    return result;
                }
            }
        }
        if (type instanceof ParameterizedType) {
            // ancestor is parameterized. Recurse only if the raw type matches the base class.
            final ParameterizedType parameterizedType = (ParameterizedType) type;
            final Type rawType = parameterizedType.getRawType();
            if (rawType instanceof Class<?>) {
                final Class<?> rawTypeClass = (Class<?>) rawType;
                if (base.isAssignableFrom(rawTypeClass)) {

                    // loop through all type arguments and replace type variables with the actually known types
                    final List<Type> resolvedTypes = new LinkedList<Type>();
                    for (Type t : parameterizedType.getActualTypeArguments()) {
                        if (t instanceof TypeVariable<?>) {
                            final Type resolvedType = genericVariables.get(((TypeVariable<?>) t).getName());
                            resolvedTypes.add(resolvedType != null ? resolvedType : t);
                        } else if (t instanceof ParameterizedType) {
                            final ParameterizedType pType = (ParameterizedType) t;
                            final Type resolvedPType = new ResolvedParameterizedType(pType, genericVariables);
                            resolvedTypes.add(resolvedPType);
                        } else {
                            resolvedTypes.add(t);
                        }
                    }

                    final Type[] result = resolveActualTypeArgs((Class<? extends T>) rawTypeClass, base,
                            resolvedTypes.toArray(new Type[] {}));
                    if (result != null) {
                        return result;
                    }
                }
            }
        }
    }

    // we have a result if we reached the base class.
    return offspring.equals(base) ? actualArgs : null;
}

From source file:org.sigmah.server.handler.base.AbstractCommandHandler.java

/**
 * {@inheritDoc}/*from  www .j  a va  2 s. c  o  m*/
 */
@SuppressWarnings("unchecked")
@Override
public final Class<C> getCommandType() {

    if (clazz == null) {
        final Class<?> clazz = Injectors.getClass(this);
        final Type type = ((ParameterizedType) clazz.getGenericSuperclass()).getActualTypeArguments()[0];

        if (type instanceof Class) {
            this.clazz = (Class<C>) type;
        } else if (type instanceof ParameterizedType) {
            // If the command handler is parametrized, retrieves the raw class.
            this.clazz = (Class<C>) ((ParameterizedType) type).getRawType();
        } else {
            throw new UnsupportedOperationException("Type is not supported: " + type);
        }
    }

    return clazz;
}

From source file:io.coala.factory.ClassUtil.java

/**
 * Get the actual type arguments a child class has used to extend a generic
 * base class. See <a/*w  w w  .  j  av  a  2  s.c  om*/
 * href="http://www.artima.com/weblogs/viewpost.jsp?thread=208860"
 * >description</a>
 * 
 * @param genericAncestorType the base class
 * @param concreteDescendantType the child class
 * @return a list of the raw classes for the actual type arguments.
 */
public static <T> List<Class<?>> getTypeArguments(final Class<T> genericAncestorType,
        final Class<? extends T> concreteDescendantType) {
    // sanity check
    if (genericAncestorType == null)
        throw CoalaExceptionFactory.VALUE_NOT_SET.createRuntime("genericAncestorType");
    if (concreteDescendantType == null)
        throw CoalaExceptionFactory.VALUE_NOT_SET.createRuntime("concreteDescendantType");

    Map<Type, Type> resolvedTypes = new HashMap<Type, Type>();
    Type type = concreteDescendantType;
    Class<?> typeClass = getClass(type);

    // start walking up the inheritance hierarchy until we hit parentClass
    while (!genericAncestorType.equals(typeClass)) {
        if (type instanceof Class) {
            // there is no useful information for us in raw types, so just
            // keep going.

            if (genericAncestorType.isInterface()) {
                Type intfType = null;
                for (Type intf : typeClass.getGenericInterfaces()) {
                    if (intf instanceof ParameterizedType
                            && genericAncestorType.equals(((ParameterizedType) intf).getRawType())) {
                        intfType = intf;
                        break;
                    }
                }
                if (intfType == null)
                    type = typeClass.getGenericSuperclass();
                else
                    type = intfType;
            } else
                type = typeClass.getGenericSuperclass();

            if (type == null) {
                if (!typeClass.isInterface()) {
                    LOG.warn("No generic super classes found for child class: " + typeClass + " of parent: "
                            + genericAncestorType);
                    return Collections.emptyList();
                }
                for (Type intf : typeClass.getGenericInterfaces()) {
                    if (intf instanceof ParameterizedType) {
                        type = intf;
                        // TODO try other interfaces if this one fails?
                        break;
                    }
                }
                if (type == null) {
                    LOG.warn("No generic ancestors found for child interface: " + typeClass + " of parent: "
                            + genericAncestorType);
                    return Collections.emptyList();
                }
            }
            // LOG.trace(String.format("Trying generic super of %s: %s",
            // typeClass.getSimpleName(), type));
        } else {
            final ParameterizedType parameterizedType = (ParameterizedType) type;
            final Class<?> rawType = (Class<?>) parameterizedType.getRawType();

            final Type[] actualTypeArguments = parameterizedType.getActualTypeArguments();
            final TypeVariable<?>[] typeParameters = rawType.getTypeParameters();
            for (int i = 0; i < actualTypeArguments.length; i++) {
                resolvedTypes.put(typeParameters[i], actualTypeArguments[i]);
            }

            if (!genericAncestorType.equals(rawType)) {
                type = rawType.getGenericSuperclass();
                // LOG.trace(String.format(
                // "Trying generic super of child %s: %s", rawType,
                // type));
            }
            // else // done climbing the hierarchy
            // LOG.trace("Matched generic " + type + " to ancestor: "
            // + genericAncestorType);
        }
        typeClass = getClass(type);
        // LOG.trace("Trying generic " + typeClass + " from: "
        // + Arrays.asList(typeClass.getGenericInterfaces()));
    }

    // finally, for each actual type argument provided to baseClass,
    // determine (if possible)
    // the raw class for that type argument.
    final Type[] actualTypeArguments;
    if (type instanceof Class) {
        actualTypeArguments = typeClass.getTypeParameters();
    } else {
        actualTypeArguments = ((ParameterizedType) type).getActualTypeArguments();
    }

    // resolve types by chasing down type variables.
    final List<Class<?>> parentTypeArguments = new ArrayList<Class<?>>();
    for (Type baseType : actualTypeArguments) {
        while (resolvedTypes.containsKey(baseType))
            baseType = resolvedTypes.get(baseType);

        parentTypeArguments.add(getClass(baseType));
    }
    // LOG.trace(String.format(
    // "Got child %s's type arguments for %s: %s",
    // childClass.getName(), parentClass.getSimpleName(),
    // parentTypeArguments));
    return parentTypeArguments;
}

From source file:com.dangdang.ddframe.job.internal.job.dataflow.AbstractDataFlowElasticJob.java

private DataFlowType getDataFlowType() {
    Class<?> target = getClass();
    while (true) {
        if (!(target.getGenericSuperclass() instanceof ParameterizedType)) {
            target = target.getSuperclass();
            continue;
        }//from  ww  w. j  a  v a  2  s.c  o  m
        ParameterizedType parameterizedType = (ParameterizedType) target.getGenericSuperclass();
        if (2 != parameterizedType.getActualTypeArguments().length) {
            target = target.getSuperclass();
            continue;
        }
        Type type = parameterizedType.getActualTypeArguments()[1];
        if (JobExecutionMultipleShardingContext.class == type) {
            return DataFlowType.THROUGHPUT;
        } else if (JobExecutionSingleShardingContext.class == type) {
            return DataFlowType.SEQUENCE;
        } else {
            throw new UnsupportedOperationException(String.format("Cannot support %s", type));
        }
    }
}