Example usage for java.lang.reflect ParameterizedType getRawType

List of usage examples for java.lang.reflect ParameterizedType getRawType

Introduction

In this page you can find the example usage for java.lang.reflect ParameterizedType getRawType.

Prototype

Type getRawType();

Source Link

Document

Returns the Type object representing the class or interface that declared this type.

Usage

From source file:com.iterranux.droolsjbpmCore.internal.AbstractGenericFactory.java

/**
 * Get the actual type arguments a child class has used to extend a generic base class.
 *
 * @param baseClass the base class//from w  w w  .  ja  va2 s .  co m
 * @param childClass the child class
 * @return a list of the raw classes for the actual type arguments.
 */
@SuppressWarnings("all")
public static <T> List<Class<?>> getTypeArguments(Class<T> baseClass, Class<? extends T> childClass) {

    Map<Type, Type> resolvedTypes = new HashMap<Type, Type>();
    Type type = childClass;
    // start walking up the inheritance hierarchy until we hit baseClass
    while (!getClass(type).equals(baseClass)) {
        if (type instanceof Class) {
            // there is no useful information for us in raw types, so just keep going.
            type = ((Class) type).getGenericSuperclass();
        } else {
            ParameterizedType parameterizedType = (ParameterizedType) type;

            Class<?> rawType = (Class) parameterizedType.getRawType();

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

            if (!rawType.equals(baseClass)) {
                type = rawType.getGenericSuperclass();
            }
        }
    }

    // finally, for each actual type argument provided to baseClass, determine (if possible)
    // the raw class for that type argument.
    Type[] actualTypeArguments;
    if (type instanceof Class) {
        actualTypeArguments = ((Class) type).getTypeParameters();
    } else {
        actualTypeArguments = ((ParameterizedType) type).getActualTypeArguments();
    }
    List<Class<?>> typeArgumentsAsClasses = new ArrayList<Class<?>>();
    // resolve types by chasing down type variables.
    for (Type baseType : actualTypeArguments) {
        while (resolvedTypes.containsKey(baseType)) {
            baseType = resolvedTypes.get(baseType);
        }
        typeArgumentsAsClasses.add(getClass(baseType));
    }
    return typeArgumentsAsClasses;
}

From source file:GenericsUtil.java

/**
 * Returns the class defined for the type variable
 * of the given name. //from   ww  w  .j a  va 2  s .  c  om
 * @param clazz the class
 * @param genericClazz the generic class or interface to check the type for
 * @param name the name of the type variable
 * @param recursive whether or not to recurse up the
 * object's inheritance hierarchy.
 * @return the class
 */
public static Class<?> getTypeVariableClassByName(Class<?> clazz, Type genericClazz, String name,
        Boolean recursive) {

    // we hit the end of the line here :)
    if (clazz == null || clazz.equals(Object.class)) {
        return null;
    }

    // loop through all of the types implemented
    for (ParameterizedType pType : getGenericTypes(clazz)) {

        // do all of them, or one of them
        if (genericClazz == null || genericClazz.equals(pType.getRawType())) {

            // get super class type variables
            TypeVariable<?>[] typeVars = getGenericTypeParameters(clazz, pType.getRawType());
            for (int i = 0; i < typeVars.length; i++) {
                if ((genericClazz == null || genericClazz.equals(typeVars[i].getGenericDeclaration()))
                        && typeVars[i].getName().equals(name)) {

                    // get the type
                    Type type = pType.getActualTypeArguments()[i];

                    if (Class.class.isAssignableFrom(type.getClass())) {
                        return (Class<?>) type;
                    } else if (ParameterizedType.class.isAssignableFrom(type.getClass())) {
                        return (Class<?>) ((ParameterizedType) type).getRawType();
                    }
                }
            }

        }

    }

    // none found
    return (recursive) ? getTypeVariableClassByName(clazz.getSuperclass(), genericClazz, name, recursive)
            : null;
}

From source file:org.apache.batchee.cli.BatchEECLI.java

private static Runnable instantiate(final Class<? extends Runnable> cmd, final CliConfiguration configuration,
        final Map<String, Field> fields, final boolean hasArgs, final CommandLine line)
        throws InstantiationException, IllegalAccessException {
    final Runnable commandInstance = cmd.newInstance();
    if (hasArgs) { // we have few commands we can execute without args even if we have a bunch of config
        for (final Map.Entry<String, Field> option : fields.entrySet()) {
            final String key = option.getKey();
            if (key.isEmpty()) { // arguments, not an option
                final List<String> list = line.getArgList();
                if (list != null) {
                    final Field field = option.getValue();
                    final Type expectedType = field.getGenericType();
                    if (ParameterizedType.class.isInstance(expectedType)) {
                        final ParameterizedType pt = ParameterizedType.class.cast(expectedType);
                        if ((pt.getRawType() == List.class || pt.getRawType() == Collection.class)
                                && pt.getActualTypeArguments().length == 1
                                && pt.getActualTypeArguments()[0] == String.class) {
                            field.set(commandInstance, list);
                        } else {
                            throw new IllegalArgumentException("@Arguments only supports List<String>");
                        }//from  w ww  . j  a va  2s  .com
                    } else {
                        throw new IllegalArgumentException("@Arguments only supports List<String>");
                    }
                }
            } else {
                final String value = line.getOptionValue(key);
                if (value != null) {
                    final Field field = option.getValue();
                    field.set(commandInstance, configuration.coerce(value, field.getGenericType()));
                }
            }
        }
    }
    return commandInstance;
}

From source file:com.feilong.core.lang.reflect.TypeUtil.java

/**
 *  generic interfaces parameterized type.
 *
 * @param klass/*  w w  w  .ja  v a2  s. co  m*/
 *            the klass
 * @param extractInterfaceClass
 *            the extract interface class
 * @return the generic interfaces parameterized type
 * @see java.lang.Class#getGenericInterfaces()
 * @see java.lang.reflect.ParameterizedType#getRawType()
 * @since 1.1.1
 */
private static ParameterizedType getGenericInterfacesParameterizedType(Class<?> klass,
        Class<?> extractInterfaceClass) {
    Validate.notNull(klass, "klass can't be null/empty!");
    Validate.notNull(extractInterfaceClass, "extractInterfaceClass can't be null/empty!");

    Type[] genericInterfaces = klass.getGenericInterfaces();
    for (Type genericInterface : genericInterfaces) {
        if (genericInterface instanceof ParameterizedType) {
            ParameterizedType genericInterfacesType = (ParameterizedType) genericInterface;
            Type rawType = genericInterfacesType.getRawType();

            if (extractInterfaceClass == rawType) {
                return genericInterfacesType;
            }
        }
    }
    return null;
}

From source file:org.synku4j.wbxml.util.WbxmlUtil.java

/**
 * Introspect the given class, extracting all the codepage information, populating the supplied collection.
 * //from  w w  w  .  j  av  a 2 s .  c om
 * @param clazz to introspect.
 * @param pages to populate.
 */
public static void introspect(final Class<?> clazz, final Collection<WbxmlCodePage> pages) {
    final WbxmlPage page = clazz.getAnnotation(WbxmlPage.class);
    if (page == null) {
        // no page means we skip it.
        return;
    }

    if (page.index() == -1) {
        return;
    }

    WbxmlField root = clazz.getAnnotation(WbxmlField.class);
    WbxmlCodePageWrapper codePage = null;
    // TODO : For the introspect use a Map, then collate to collection
    for (WbxmlCodePage cp : pages) {
        if (cp.getIndex() == page.index()) {
            codePage = (WbxmlCodePageWrapper) cp;
            break;
        }
    }

    if (codePage == null) {
        codePage = new WbxmlCodePageWrapper(page);
        pages.add(codePage);
    }

    if (root != null) {
        codePage.addCodePageField(new WbxmlCodePageFieldWrapper(page, root, clazz));
    }

    // Parse from the root down
    for (Field field : WbxmlUtil.getFields(clazz)) {
        final WbxmlField wbxmlField = field.getAnnotation(WbxmlField.class);
        final Type type = field.getGenericType();
        if (type instanceof ParameterizedType) {
            ParameterizedType ptype = (ParameterizedType) type;
            Type rawType = ptype.getRawType();

            if (Collection.class.isAssignableFrom((Class<?>) rawType)) {
                Type[] args = ptype.getActualTypeArguments();
                if (args != null && args.length > 0) {
                    for (Type arg : args) {
                        if (arg instanceof Class<?>) {
                            introspect((Class<?>) arg, pages);
                        }
                    }
                }
            }
        } else if (type instanceof Class<?>) {
            introspect((Class<?>) type, pages);
        }

        // if the class has a page, add it to the codepage.
        Class<?> modelClass = null;
        if (type instanceof Class<?>) {
            if (((Class<?>) type).getAnnotation(WbxmlPage.class) != null) {
                modelClass = (Class<?>) type;
            }
        }

        codePage.addCodePageField(new WbxmlCodePageFieldWrapper(page, wbxmlField, modelClass));
    }
}

From source file:com.feilong.commons.core.lang.reflect.TypeUtil.java

/**
 *  generic interfaces parameterized type.
 *
 * @param klass/*from  w  ww  .j  av  a2  s  .  c om*/
 *            the klass
 * @param extractInterfaceClass
 *            the extract interface class
 * @return the generic interfaces parameterized type
 * @see java.lang.Class#getGenericInterfaces()
 * @see java.lang.reflect.ParameterizedType#getRawType()
 * @since 1.1.1
 */
private static ParameterizedType getGenericInterfacesParameterizedType(Class<?> klass,
        Class<?> extractInterfaceClass) {

    if (Validator.isNullOrEmpty(klass)) {
        throw new NullPointerException("klass can't be null/empty!");
    }

    Type[] genericInterfaces = klass.getGenericInterfaces();
    for (Type genericInterface : genericInterfaces) {
        if (genericInterface instanceof ParameterizedType) {
            ParameterizedType genericInterfacesType = (ParameterizedType) genericInterface;
            Type rawType = genericInterfacesType.getRawType();

            if (extractInterfaceClass == rawType) {
                return genericInterfacesType;
            }
        }
    }
    return null;
}

From source file:com.arpnetworking.jackson.BuilderDeserializer.java

private static void addTo(final Set<Type> visited, final Map<Class<?>, JsonDeserializer<?>> deserializerMap,
        final Type targetType) {
    if (visited.contains(targetType)) {
        return;/*w w  w  . j a  v a  2 s.c o m*/
    }
    visited.add(targetType);

    if (targetType instanceof Class<?>) {
        @SuppressWarnings("unchecked")
        final Class<Object> targetClass = (Class<Object>) targetType;
        try {
            // Look-up and register the builder for this class
            final Class<? extends Builder<? extends Object>> builderClass = getBuilderForClass(targetClass);
            deserializerMap.put(targetClass, BuilderDeserializer.of(builderClass));

            LOGGER.info("Registered builder for class; builderClass=" + builderClass + " targetClass="
                    + targetClass);

            // Process all setters on the builder
            for (final Method method : builderClass.getMethods()) {
                if (isSetterMethod(builderClass, method)) {
                    final Type setterArgumentType = method.getGenericParameterTypes()[0];
                    // Recursively register builders for each setter's type
                    addTo(visited, deserializerMap, setterArgumentType);
                }
            }
        } catch (final ClassNotFoundException e) {
            // Log that the class is not build-able
            LOGGER.debug("Ignoring class without builder; targetClass=" + targetClass);
        }

        // Support for JsonSubTypes annotation
        if (targetClass.isAnnotationPresent(JsonSubTypes.class)) {
            final JsonSubTypes.Type[] subTypes = targetClass.getAnnotation(JsonSubTypes.class).value();
            for (final JsonSubTypes.Type subType : subTypes) {
                addTo(visited, deserializerMap, subType.value());
            }
        }

        // Support for JsonTypeInfo annotation
        // TODO(vkoskela): Support JsonTypeInfo classpath scan [MAI-116]
    }

    if (targetType instanceof ParameterizedType) {
        // Recursively register builders for each parameterized type
        final ParameterizedType targetParameterizedType = (ParameterizedType) targetType;
        final Type rawType = targetParameterizedType.getRawType();
        addTo(visited, deserializerMap, rawType);
        for (final Type argumentActualType : targetParameterizedType.getActualTypeArguments()) {
            addTo(visited, deserializerMap, argumentActualType);
        }
    }
}

From source file:org.opencb.commons.utils.CommandLineUtils.java

private static String getType(Type genericType) {
    String type;/*w  w w . j a  v a2  s . c o  m*/
    if (genericType instanceof ParameterizedType) {
        ParameterizedType parameterizedType = (ParameterizedType) genericType;
        Type rawType = parameterizedType.getRawType();
        if (rawType instanceof Class && Collection.class.isAssignableFrom((Class) rawType)) {
            return getType(parameterizedType.getActualTypeArguments()[0]) + "*";
        }
    }
    type = genericType.getTypeName();
    type = type.substring(1 + Math.max(type.lastIndexOf("."), type.lastIndexOf("$")));
    type = Arrays.asList(org.apache.commons.lang3.StringUtils.splitByCharacterTypeCamelCase(type)).stream()
            .map(String::toUpperCase).collect(Collectors.joining("_"));

    if (type.equals("INTEGER")) {
        type = "INT";
    }
    return type;
}

From source file:com.autentia.common.util.ClassWithList.java

private static void print(ParameterizedType pt) {
    System.out.println("Parameterized type");
    System.out.println("Owner: " + pt.getOwnerType());
    System.out.println("Raw type: " + pt.getRawType());

    for (Type actualType : pt.getActualTypeArguments()) {
        print(actualType);//from   w ww  .  j a v a2  s.  c o m
    }
}

From source file:org.grouplens.grapht.util.Types.java

/**
 * Compute the erasure of a type./* www.j  a v a 2 s .  c o  m*/
 * 
 * @param type The type to erase.
 * @return The class representing the erasure of the type.
 * @throws IllegalArgumentException if <var>type</var> is unerasable (e.g.
 *             it is a type variable or a wildcard).
 */
public static Class<?> erase(Type type) {
    if (type instanceof Class) {
        return (Class<?>) type;
    } else if (type instanceof ParameterizedType) {
        ParameterizedType pt = (ParameterizedType) type;
        Type raw = pt.getRawType();
        try {
            return (Class<?>) raw;
        } catch (ClassCastException e) {
            throw new RuntimeException("raw type not a Class", e);
        }
    } else {
        throw new IllegalArgumentException();
    }
}