Example usage for java.lang Class getGenericInterfaces

List of usage examples for java.lang Class getGenericInterfaces

Introduction

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

Prototype

public Type[] getGenericInterfaces() 

Source Link

Document

Returns the Type s representing the interfaces directly implemented by the class or interface represented by this object.

Usage

From source file:org.op4j.devutils.selected.ImplFile.java

public void computeMethodImplementations(final ImplType implType, final Class<?> interfaceClass)
        throws Exception {

    final List<Method> interfaceMethods = new ArrayList<Method>();
    interfaceMethods.addAll(Arrays.asList(interfaceClass.getDeclaredMethods()));

    final Set<Type> extendedInterfaces = new HashSet<Type>(
            Arrays.asList(interfaceClass.getGenericInterfaces()));
    Type getReturnType = null;//w  w  w .j  av a  2 s. co  m
    for (final Type extendedInterface : extendedInterfaces) {
        if (extendedInterface instanceof ParameterizedType) {
            final ParameterizedType pType = (ParameterizedType) extendedInterface;
            if (((Class<?>) pType.getRawType()).equals(UniqOperator.class)) {
                getReturnType = pType.getActualTypeArguments()[0];
            }
        }
    }

    try {
        interfaceMethods.add(UniqOpOperator.class.getMethod("get"));
    } catch (NoSuchMethodException e) {
        // nothing to do
    }

    if (this.className.contains("Array")) {
        this.element = "T[]";
    } else if (this.className.contains("List")) {
        this.element = "List<T>";
    } else if (this.className.contains("Set")) {
        this.element = "Set<T>";
    } else if (this.className.contains("Map")) {
        this.element = "Map<K,V>";
    } else {
        this.element = "T";
    }

    for (final Method interfaceMethod : interfaceMethods) {

        final String methodName = interfaceMethod.getName();
        this.methodNames.add(methodName);

        final Type[] parameterTypes = interfaceMethod.getGenericParameterTypes();

        if (methodName.startsWith("exec")) {
            this.currentLevelType = (new TypeRep(
                    ((WildcardType) ((ParameterizedType) parameterTypes[0]).getActualTypeArguments()[0])
                            .getLowerBounds()[0])).getStringRep();
            if (this.currentLevelType.endsWith("[]")) {
                this.currentLevelElement = this.currentLevelType.substring(0,
                        this.currentLevelType.length() - 2);
            } else if (this.currentLevelType.startsWith("List<") && this.currentLevelType.endsWith(">")) {
                this.currentLevelElement = this.currentLevelType.substring(5,
                        this.currentLevelType.length() - 1);
            } else if (this.currentLevelType.startsWith("Set<") && this.currentLevelType.endsWith(">")) {
                this.currentLevelElement = this.currentLevelType.substring(4,
                        this.currentLevelType.length() - 1);
            } else if (this.currentLevelType.startsWith("Map<") && this.currentLevelType.endsWith(">")) {
                this.currentLevelElement = "Map.Entry<"
                        + this.currentLevelType.substring(4, this.currentLevelType.length() - 1) + ">";
            } else {
                this.currentLevelElement = "%%CURRENTELEMENTSHOULDNOTBEHERE%%";
            }
        }

        final String returnTypeStr = (methodName.equals("get")
                ? (implType == ImplType.OP ? this.element : "Function<I," + this.element + ">")
                : (methodName.equals("getAsArrayOf")
                        ? (implType == ImplType.OP ? this.element + "[]" : "Function<I," + this.element + "[]>")
                        : (methodName.equals("getAsList")
                                ? (implType == ImplType.OP ? "List<" + this.element + ">"
                                        : "Function<I,List<" + this.element + ">>")
                                : new TypeRep(interfaceMethod.getGenericReturnType()).getStringRep()
                                        .replaceAll("ILevel", "Level"))));

        final StringBuilder parameterStrBuilder = new StringBuilder();
        parameterStrBuilder.append("(");

        List<String> normalisedParamTypes = new ArrayList<String>();
        List<String> normalisedRawParamTypes = new ArrayList<String>();
        for (int j = 0; j < parameterTypes.length; j++) {
            normalisedParamTypes.add(getNormalisedParamType(parameterTypes[j], methodName, j));
            normalisedRawParamTypes.add(
                    StringUtils.substringBefore(getNormalisedParamType(parameterTypes[j], methodName, j), "<"));
        }

        String[] paramNamesForMethod = paramNames
                .get(methodName + "%" + StringUtils.join(normalisedRawParamTypes, ","));
        if (paramNamesForMethod == null) {
            paramNamesForMethod = paramNames.get(methodName + "%" + parameterTypes.length);
            if (paramNamesForMethod == null) {
                paramNamesForMethod = paramNames.get(methodName);
            }
        }

        for (int j = 0; j < normalisedParamTypes.size(); j++) {

            if (j > 0) {
                parameterStrBuilder.append(", ");
            }

            parameterStrBuilder.append("final " + normalisedParamTypes.get(j) + " ");

            if (paramNamesForMethod == null) {
                throw new RuntimeException("No name for parameter " + j + " of method " + methodName
                        + " in interface " + this.interfaceTypeRep.getStringRep());
            }
            parameterStrBuilder.append(paramNamesForMethod[j]);

        }
        parameterStrBuilder.append(")");

        final StringBuilder strBuilder = new StringBuilder();
        strBuilder.append(
                "    public " + returnTypeStr + " " + methodName + parameterStrBuilder.toString() + " {\n");
        strBuilder.append("        return null;\n");
        strBuilder.append("    }\n");

        this.methodImplementations.add(strBuilder.toString());

    }

}

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  av  a  2  s  .  co m
 * @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.seedstack.scheduler.internal.SchedulerPlugin.java

/**
 * Returns the type parameter of the TaskListener interface.
 *
 * @param listenerClass class to check//from w w  w.j  ava  2  s.  com
 * @return type which extends Task
 * @throws SeedException if no parameter type is present
 */
private Type getParametrizedTypeOfJobListener(Class<?> listenerClass) {
    Type[] interfaces = listenerClass.getGenericInterfaces();
    Type[] typeParameters = null;
    for (Type anInterface : interfaces) {
        // Checks if the class get parameters
        if (!(anInterface instanceof ParameterizedType)) {
            continue;
        }
        // Gets rawType to check if the interface is TaskListener
        Class interfaceClass = (Class) ((ParameterizedType) anInterface).getRawType();
        if (TaskListener.class.isAssignableFrom(interfaceClass)) {
            typeParameters = ((ParameterizedType) anInterface).getActualTypeArguments();
            break;
        }
    }
    if (typeParameters == null || typeParameters.length == 0) {
        throw SeedException.createNew(SchedulerErrorCode.MISSING_TYPE_PARAMETER).put("class", listenerClass);
    }

    return typeParameters[0];
}

From source file:org.seedstack.seed.core.internal.data.DataPlugin.java

private Class getTypeParameter(Class<?> scannedDataImporterClass, Class<?> genericInterface) {
    Class actualType = null;/*from   w  ww.j a va 2s  .  c o m*/
    // Get all generic interfaces implemented by the scanned class
    Type[] genericInterfaces = scannedDataImporterClass.getGenericInterfaces();
    for (Type type : genericInterfaces) {
        if (type instanceof ParameterizedType) {
            Class anInterface = (Class) ((ParameterizedType) type).getRawType();
            // If the interface is DataImporter get its type parameter
            if (genericInterface.isAssignableFrom(anInterface)) {
                actualType = (Class) ((ParameterizedType) type).getActualTypeArguments()[0];
            }
        }
    }
    return actualType;
}

From source file:org.seedstack.seed.scheduler.internal.SchedulerPlugin.java

/**
 * Return the type parameter of the TaskListener interface.
 *
 * @param listenerClass class to check//from  w  w w  .ja  v  a  2s. c o  m
 * @return type which extends Task
 * @throws SeedException if no parameter type is present
 */
@SuppressWarnings("ThrowableResultOfMethodCallIgnored")
private Type getParametrizedTypeOfJobListener(Class<?> listenerClass) {
    Type[] interfaces = listenerClass.getGenericInterfaces();
    Type[] typeParameters = null;
    for (Type anInterface : interfaces) {
        // Checks if the class get parameters
        if (!(anInterface instanceof ParameterizedType)) {
            continue;
        }
        // Gets rawType to check if the interface is TaskListener
        Class interfaceClass = (Class) ((ParameterizedType) anInterface).getRawType();
        if (TaskListener.class.isAssignableFrom(interfaceClass)) {
            typeParameters = ((ParameterizedType) anInterface).getActualTypeArguments();
            break;
        }
    }
    if (typeParameters == null || typeParameters.length == 0) {
        throw SeedException.createNew(SchedulerErrorCode.MISSING_TYPE_PARAMETER).put("class", listenerClass);
    }

    return typeParameters[0];
}

From source file:org.soybeanMilk.SbmUtils.java

/**
 * ???// w  ww .ja v  a 2s  . c o m
 * <pre>
 * class A&lt;T&gt;{}
 * class B extends A&lt;Integer&gt;{}
 * </pre>
 * <code>extractTypeVariablesInType(B.class, map)</code><code>map</code>
 * <pre>
 * T    -------&gt;    Integer
 * </pre>
 * @param source
 * @param container
 * @date 2012-5-14
 */
private static void extractTypeVariablesInType(Type source, Map<TypeVariable<?>, Type> variableTypesMap) {
    if (source == null)
        return;
    else if (source instanceof Class<?>) {
        Class<?> clazz = (Class<?>) source;

        //?
        Type[] genericInterfaces = clazz.getGenericInterfaces();
        if (genericInterfaces != null) {
            for (Type t : genericInterfaces)
                extractTypeVariablesInType(t, variableTypesMap);
        }

        //
        Type genericSuperType = clazz.getGenericSuperclass();
        Class<?> superClass = clazz.getSuperclass();
        while (superClass != null && !Object.class.equals(superClass)) {
            extractTypeVariablesInType(genericSuperType, variableTypesMap);

            genericSuperType = superClass.getGenericSuperclass();
            superClass = superClass.getSuperclass();
        }

        //
        Class<?> outerClass = clazz;
        while (outerClass.isMemberClass()) {
            Type genericOuterType = outerClass.getGenericSuperclass();
            extractTypeVariablesInType(genericOuterType, variableTypesMap);

            outerClass = outerClass.getEnclosingClass();
        }
    } else if (source instanceof ParameterizedType) {
        ParameterizedType pt = (ParameterizedType) source;

        if (isClassType(pt.getRawType())) {
            Type[] actualArgTypes = pt.getActualTypeArguments();
            TypeVariable<?>[] typeVariables = narrowToClass(pt.getRawType()).getTypeParameters();

            for (int i = 0; i < actualArgTypes.length; i++) {
                TypeVariable<?> var = typeVariables[i];
                Type value = actualArgTypes[i];

                //????
                if (value instanceof TypeVariable<?>) {
                    Type actual = variableTypesMap.get(value);

                    if (actual != null)
                        value = actual;
                }

                variableTypesMap.put(var, value);
            }
        }

        //??
        extractTypeVariablesInType(pt.getRawType(), variableTypesMap);
    }
}

From source file:org.springframework.core.GenericTypeResolver.java

private static Class[] doResolveTypeArguments(Class ownerClass, Class classToIntrospect, Class genericIfc) {
    while (classToIntrospect != null) {
        if (genericIfc.isInterface()) {
            Type[] ifcs = classToIntrospect.getGenericInterfaces();
            for (Type ifc : ifcs) {
                Class[] result = doResolveTypeArguments(ownerClass, ifc, genericIfc);
                if (result != null) {
                    return result;
                }//  w w  w.  java  2 s. c om
            }
        } else {
            Class[] result = doResolveTypeArguments(ownerClass, classToIntrospect.getGenericSuperclass(),
                    genericIfc);
            if (result != null) {
                return result;
            }
        }
        classToIntrospect = classToIntrospect.getSuperclass();
    }
    return null;
}

From source file:org.springframework.core.GenericTypeResolver.java

/**
 * Build a mapping of {@link TypeVariable#getName TypeVariable names} to
 * {@link Class concrete classes} for the specified {@link Class}. Searches
 * all super types, enclosing types and interfaces.
 *///ww w . ja v  a2s  . c o m
public static Map<TypeVariable, Type> getTypeVariableMap(Class clazz) {
    Map<TypeVariable, Type> ref = typeVariableCache.get(clazz);
    Map<TypeVariable, Type> typeVariableMap = (ref != null ? ref : null);

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

        // interfaces
        extractTypeVariablesFromGenericInterfaces(clazz.getGenericInterfaces(), typeVariableMap);

        // super class
        Type genericType = clazz.getGenericSuperclass();
        Class type = clazz.getSuperclass();
        while (type != null && !Object.class.equals(type)) {
            if (genericType instanceof ParameterizedType) {
                ParameterizedType pt = (ParameterizedType) genericType;
                populateTypeMapFromParameterizedType(pt, typeVariableMap);
            }
            extractTypeVariablesFromGenericInterfaces(type.getGenericInterfaces(), typeVariableMap);
            genericType = type.getGenericSuperclass();
            type = type.getSuperclass();
        }

        // enclosing class
        type = clazz;
        while (type.isMemberClass()) {
            genericType = type.getGenericSuperclass();
            if (genericType instanceof ParameterizedType) {
                ParameterizedType pt = (ParameterizedType) genericType;
                populateTypeMapFromParameterizedType(pt, typeVariableMap);
            }
            type = type.getEnclosingClass();
        }

        typeVariableCache.put(clazz, typeVariableMap);
    }

    return typeVariableMap;
}

From source file:org.statefulj.framework.core.StatefulFactory.java

/**
 * @param entityToRepositoryMapping/*  w ww .  j a va  2  s.c om*/
 * @param bfName
 * @param bf
 * @throws ClassNotFoundException
 */
private void mapEntityToRepository(Map<Class<?>, String> entityToRepositoryMapping, String bfName,
        BeanDefinition bf) throws ClassNotFoundException {

    // Determine the Entity Class associated with the Repo
    //
    String value = (String) bf.getAttribute("factoryBeanObjectType");
    Class<?> repoInterface = Class.forName(value);
    Class<?> entityType = null;
    for (Type type : repoInterface.getGenericInterfaces()) {
        if (type instanceof ParameterizedType) {
            ParameterizedType parmType = (ParameterizedType) type;
            if (Repository.class.isAssignableFrom((Class<?>) parmType.getRawType())
                    && parmType.getActualTypeArguments() != null
                    && parmType.getActualTypeArguments().length > 0) {
                entityType = (Class<?>) parmType.getActualTypeArguments()[0];
                break;
            }
        }
    }

    if (entityType == null) {
        throw new RuntimeException("Unable to determine Entity type for class " + repoInterface.getName());
    }

    // Map Entity to the RepositoryFactoryBeanSupport bean
    //
    logger.debug("Mapped \"{}\" to repo \"{}\", beanId=\"{}\"", entityType.getName(), value, bfName);

    entityToRepositoryMapping.put(entityType, bfName);
}

From source file:org.tinygroup.tinyioc.impl.BeanContainerImpl.java

public static boolean isSubClass(Class a, Class b) {
    Type genericSuperclass = a.getGenericSuperclass();
    for (Type type : a.getGenericInterfaces()) {
        if (type.equals(b)) {
            return true;
        }/*from w  ww  .ja v a2s  .co  m*/
        boolean is = isSubClass((Class) type, b);
        if (is) {
            return true;
        }
    }
    if (genericSuperclass != null) {
        if (genericSuperclass.equals(b)) {
            return true;
        } else {
            boolean is = isSubClass((Class) genericSuperclass, b);
            if (is) {
                return true;
            }
        }
    }
    return false;
}