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: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
 * /* ww w  . jav  a  2 s . c o 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.springframework.core.GenericTypeResolver.java

/**
 * Read the {@link TypeVariable TypeVariables} from the supplied {@link ParameterizedType}
 * and add mappings corresponding to the {@link TypeVariable#getName TypeVariable name} ->
 * concrete type to the supplied {@link Map}.
 * <p>Consider this case://ww  w .  j av a 2s  .co  m
 * <pre class="code>
 * public interface Foo<S, T> {
 *  ..
 * }
 *
 * public class FooImpl implements Foo<String, Integer> {
 *  ..
 * }</pre>
 * For '{@code FooImpl}' the following mappings would be added to the {@link Map}:
 * {S=java.lang.String, T=java.lang.Integer}.
 */
private static void populateTypeMapFromParameterizedType(ParameterizedType type,
        Map<TypeVariable, Type> typeVariableMap) {
    if (type.getRawType() instanceof Class) {
        Type[] actualTypeArguments = type.getActualTypeArguments();
        TypeVariable[] typeVariables = ((Class) type.getRawType()).getTypeParameters();
        for (int i = 0; i < actualTypeArguments.length; i++) {
            Type actualTypeArgument = actualTypeArguments[i];
            TypeVariable variable = typeVariables[i];
            if (actualTypeArgument instanceof Class) {
                typeVariableMap.put(variable, actualTypeArgument);
            } else if (actualTypeArgument instanceof GenericArrayType) {
                typeVariableMap.put(variable, actualTypeArgument);
            } else if (actualTypeArgument instanceof ParameterizedType) {
                typeVariableMap.put(variable, actualTypeArgument);
            } else if (actualTypeArgument instanceof TypeVariable) {
                // We have a type that is parameterized at instantiation time
                // the nearest match on the bridge method will be the bounded type.
                TypeVariable typeVariableArgument = (TypeVariable) actualTypeArgument;
                Type resolvedType = typeVariableMap.get(typeVariableArgument);
                if (resolvedType == null) {
                    resolvedType = extractBoundForTypeVariable(typeVariableArgument);
                }
                typeVariableMap.put(variable, resolvedType);
            }
        }
    }
}

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

/**
 * Populates the {@code map} with variable/argument pairs for the given {@code type}.
 *//*from  w w  w .  j  av a 2  s. com*/
private static void populateTypeArgs(ParameterizedType type, Map<TypeVariable<?>, Type> map,
        boolean depthFirst) {
    if (type.getRawType() instanceof Class) {
        TypeVariable<?>[] typeVariables = ((Class<?>) type.getRawType()).getTypeParameters();
        Type[] typeArguments = type.getActualTypeArguments();

        if (type.getOwnerType() != null) {
            Type owner = type.getOwnerType();
            if (owner instanceof ParameterizedType)
                populateTypeArgs((ParameterizedType) owner, map, depthFirst);
        }

        for (int i = 0; i < typeArguments.length; i++) {
            TypeVariable<?> variable = typeVariables[i];
            Type typeArgument = typeArguments[i];

            if (typeArgument instanceof Class) {
                map.put(variable, typeArgument);
            } else if (typeArgument instanceof GenericArrayType) {
                map.put(variable, typeArgument);
            } else if (typeArgument instanceof ParameterizedType) {
                map.put(variable, typeArgument);
            } else if (typeArgument instanceof TypeVariable) {
                TypeVariable<?> typeVariableArgument = (TypeVariable<?>) typeArgument;
                if (depthFirst) {
                    Type existingType = map.get(variable);
                    if (existingType != null) {
                        map.put(typeVariableArgument, existingType);
                        continue;
                    }
                }

                Type resolvedType = map.get(typeVariableArgument);
                if (resolvedType == null)
                    resolvedType = resolveBound(typeVariableArgument);
                map.put(variable, resolvedType);
            }
        }
    }
}

From source file:org.jiemamy.utils.reflect.GenericUtil.java

/**
 * {@code type}??{@code clazz}?????{@code true}?
 * ?????{@code false}??/*from   w w w.java  2s  .  co  m*/
 * 
 * @param type 
 * @param clazz 
 * @return {@code type}??{@code clazz}?????{@code true}
 * @throws IllegalArgumentException ?{@code null}???
 */
public static boolean isTypeOf(Type type, Class<?> clazz) {
    Validate.notNull(clazz);
    if (Class.class.isInstance(type)) {
        return clazz.isAssignableFrom(Class.class.cast(type));
    }
    if (ParameterizedType.class.isInstance(type)) {
        ParameterizedType parameterizedType = ParameterizedType.class.cast(type);
        return isTypeOf(parameterizedType.getRawType(), clazz);
    }
    return false;
}

From source file:jp.terasoluna.fw.util.GenericsUtil.java

/**
 * ??????? <code>ParameterizedType</code>???
 * @param <T> ???/*w w  w. java 2s . c om*/
 * @param genericClass ??
 * @param descendantClass <code>genericsClass</code>?? ???
 * @return ??????? <code>ParameterizedType</code>?
 * @throws IllegalStateException <code>descendantClass</code>? ??????????? <code>genercClass</code>
 *             ????? ?????
 */
protected static <T> List<ParameterizedType> getAncestorTypeList(Class<T> genericClass,
        Class<? extends T> descendantClass) throws IllegalStateException {
    List<ParameterizedType> ancestorTypeList = new ArrayList<ParameterizedType>();
    Class<?> clazz = descendantClass;
    boolean isInterface = genericClass.isInterface();

    while (clazz != null) {
        Type type = clazz.getGenericSuperclass();
        if (checkParameterizedType(type, genericClass, ancestorTypeList)) {
            break;
        }

        // ??????
        // ??????
        if (!isInterface) {
            clazz = clazz.getSuperclass();
            continue;
        }
        if (checkInterfaceAncestors(genericClass, ancestorTypeList, clazz)) {
            break;
        }

        // ???????????
        // ????????
        // ?????????????
        // ??????????
        // ???Generics?API?????????????
        // ?????????
        clazz = clazz.getSuperclass();
    }

    // ?????
    // AbstractBLogic<P, R>
    if (ancestorTypeList.isEmpty()) {
        throw new IllegalStateException(
                "Argument 'genericClass'(" + genericClass.getName() + ") does not declare type parameter");
    }

    // ???????????????
    // ??????????
    // ???Generics?API?????????????
    // ?????????
    ParameterizedType targetType = ancestorTypeList.get(ancestorTypeList.size() - 1);
    if (!targetType.getRawType().equals(genericClass)) {
        throw new IllegalStateException("Class(" + descendantClass.getName()
                + ") is not concrete class of Class(" + genericClass.getName() + ")");
    }
    return ancestorTypeList;
}

From source file:com.wavemaker.json.type.reflect.ReflectTypeUtils.java

/**
 * Initializes a TypeDefinition from a given class. The first entry in the return list is the TypeDefinition for the
 * parameter class; any entries after that (if any) are TypeDefinitions for any other types that were required as
 * fields for that root TypeDefinition.//from w w w  .  j av  a  2 s.c o m
 * 
 * @param klass The Class object to describe.
 * @param typeState The TypeState for the current operation.
 * @param strict True indicates that processing should stop on ambiguous entries; false indicates that null should
 *        be entered.
 * @return A list of TypeDefinitions; the first entry is the root (corresponding with the klass parameter), any
 *         other entries in the list were required to describe the root TypeDefinition's fields. The return may also
 *         be null, if sufficient information was not provided to determine the type.
 */
public static TypeDefinition getTypeDefinition(Type type, TypeState typeState, boolean strict) {

    Class<?> klass;

    // we already know about this type; we're done
    if (typeState.isTypeKnown(ReflectTypeUtils.getTypeName(type))) {
        return typeState.getType(ReflectTypeUtils.getTypeName(type));
    }

    // if the type is Object, return null, we can't figure out anything more
    if (type instanceof Class && Object.class.equals(type)) {
        return null;
    }

    // if we don't have enough information, return null
    if (!strict) {
        if (type instanceof Class && Map.class.isAssignableFrom((Class<?>) type)
                && !Properties.class.isAssignableFrom((Class<?>) type)) {
            if (!JSON.class.isAssignableFrom((Class<?>) type)) {
                logger.warn(MessageResource.JSON_TYPE_NOGENERICS.getMessage(type));
            }
            return null;
        } else if (type instanceof Class && List.class.isAssignableFrom((Class<?>) type)) {
            if (!JSON.class.isAssignableFrom((Class<?>) type)) {
                logger.warn(MessageResource.JSON_TYPE_NOGENERICS.getMessage(type));
            }
            return null;
        }
    }

    TypeDefinition ret;

    if (type instanceof Class && Properties.class.isAssignableFrom((Class<?>) type)) {
        MapReflectTypeDefinition mtdret = new MapReflectTypeDefinition();
        mtdret.setTypeName(ReflectTypeUtils.getTypeName(type));
        mtdret.setShortName(ReflectTypeUtils.getShortName(type));
        typeState.addType(mtdret);

        klass = (Class<?>) type;
        mtdret.setKlass(klass);

        TypeDefinition stringType = getTypeDefinition(String.class, typeState, false);
        mtdret.setKeyFieldDefinition(new GenericFieldDefinition(stringType));
        mtdret.setValueFieldDefinition(new GenericFieldDefinition(stringType));

        ret = mtdret;
    } else if (type instanceof Class && JSONUtils.isPrimitive((Class<?>) type)) {
        PrimitiveReflectTypeDefinition ptret;
        if (((Class<?>) type).isEnum()) {
            ptret = new EnumPrimitiveReflectTypeDefinition();
        } else {
            ptret = new PrimitiveReflectTypeDefinition();
        }

        ptret.setTypeName(ReflectTypeUtils.getTypeName(type));
        ptret.setShortName(ReflectTypeUtils.getShortName(type));
        typeState.addType(ptret);

        klass = (Class<?>) type;
        ptret.setKlass(klass);

        ret = ptret;
    } else if (type instanceof Class) {
        klass = (Class<?>) type;

        if (Collection.class.isAssignableFrom(klass)) {
            throw new WMRuntimeException(MessageResource.JSON_TYPE_NOGENERICS, klass);
        } else if (klass.isArray()) {
            throw new WMRuntimeException(MessageResource.JSON_USE_FIELD_FOR_ARRAY, klass);
        } else if (Map.class.isAssignableFrom(klass)) {
            throw new WMRuntimeException(MessageResource.JSON_TYPE_NOGENERICS, klass);
        } else if (ClassUtils.isPrimitiveOrWrapper(klass) || CharSequence.class.isAssignableFrom(klass)) {
            PrimitiveReflectTypeDefinition ptret = new PrimitiveReflectTypeDefinition();
            ptret.setTypeName(ReflectTypeUtils.getTypeName(type));
            ptret.setShortName(ReflectTypeUtils.getShortName(type));
            typeState.addType(ptret);

            ptret.setKlass(klass);

            ret = ptret;
        } else {
            ObjectReflectTypeDefinition otret = new ObjectReflectTypeDefinition();
            otret.setTypeName(ReflectTypeUtils.getTypeName(type));
            otret.setShortName(ReflectTypeUtils.getShortName(type));
            otret.setKlass(klass);
            typeState.addType(otret);

            PropertyUtilsBean pub = ((ReflectTypeState) typeState).getPropertyUtilsBean();
            PropertyDescriptor[] pds = pub.getPropertyDescriptors(klass);
            otret.setFields(new LinkedHashMap<String, FieldDefinition>(pds.length));

            for (PropertyDescriptor pd : pds) {
                if (pd.getName().equals("class")) {
                    continue;
                }

                Type paramType;
                if (pd.getReadMethod() != null) {
                    paramType = pd.getReadMethod().getGenericReturnType();
                } else if (pd.getWriteMethod() != null) {
                    paramType = pd.getWriteMethod().getGenericParameterTypes()[0];
                } else {
                    logger.warn("No getter in type " + pd.getName());
                    continue;
                }

                otret.getFields().put(pd.getName(),
                        getFieldDefinition(paramType, typeState, strict, pd.getName()));
            }

            ret = otret;
        }
    } else if (type instanceof ParameterizedType) {
        ParameterizedType pt = (ParameterizedType) type;

        if (pt.getRawType() instanceof Class && Map.class.isAssignableFrom((Class<?>) pt.getRawType())) {
            MapReflectTypeDefinition mtdret = new MapReflectTypeDefinition();
            mtdret.setTypeName(ReflectTypeUtils.getTypeName(type));
            mtdret.setShortName(ReflectTypeUtils.getShortName(type));
            typeState.addType(mtdret);

            Type[] types = pt.getActualTypeArguments();

            mtdret.setKeyFieldDefinition(getFieldDefinition(types[0], typeState, strict, null));
            mtdret.setValueFieldDefinition(getFieldDefinition(types[1], typeState, strict, null));
            mtdret.setKlass((Class<?>) pt.getRawType());

            ret = mtdret;
        } else {
            throw new WMRuntimeException(MessageResource.JSON_TYPE_UNKNOWNRAWTYPE, pt.getOwnerType(), pt);
        }
    } else {
        throw new WMRuntimeException(MessageResource.JSON_TYPE_UNKNOWNPARAMTYPE, type,
                type != null ? type.getClass() : null);
    }

    return ret;
}

From source file:org.apache.hadoop.hive.serde2.typeinfo.TypeInfoUtils.java

private static TypeInfo getExtendedTypeInfoFromJavaType(Type t, Method m) {

    if (t == Object.class) {
        return TypeInfoFactory.unknownTypeInfo;
    }/*from   ww w  . j  a va 2  s .c  o  m*/

    if (t instanceof ParameterizedType) {
        ParameterizedType pt = (ParameterizedType) t;
        if (List.class == (Class<?>) pt.getRawType() || ArrayList.class == (Class<?>) pt.getRawType()) {
            return TypeInfoFactory
                    .getListTypeInfo(getExtendedTypeInfoFromJavaType(pt.getActualTypeArguments()[0], m));
        }
        if (Map.class == (Class<?>) pt.getRawType() || HashMap.class == (Class<?>) pt.getRawType()) {
            return TypeInfoFactory.getMapTypeInfo(
                    getExtendedTypeInfoFromJavaType(pt.getActualTypeArguments()[0], m),
                    getExtendedTypeInfoFromJavaType(pt.getActualTypeArguments()[1], m));
        }
        t = pt.getRawType();
    }

    if (!(t instanceof Class)) {
        throw new RuntimeException("Hive does not understand type " + t + " from " + m);
    }
    Class<?> c = (Class<?>) t;

    if (PrimitiveObjectInspectorUtils.isPrimitiveJavaType(c)) {
        return TypeInfoUtils
                .getTypeInfoFromObjectInspector(PrimitiveObjectInspectorFactory.getPrimitiveJavaObjectInspector(
                        PrimitiveObjectInspectorUtils.getTypeEntryFromPrimitiveJavaType(c).primitiveCategory));
    }

    if (PrimitiveObjectInspectorUtils.isPrimitiveJavaClass(c)) {
        return TypeInfoUtils
                .getTypeInfoFromObjectInspector(PrimitiveObjectInspectorFactory.getPrimitiveJavaObjectInspector(
                        PrimitiveObjectInspectorUtils.getTypeEntryFromPrimitiveJavaClass(c).primitiveCategory));
    }

    if (PrimitiveObjectInspectorUtils.isPrimitiveWritableClass(c)) {
        return TypeInfoUtils.getTypeInfoFromObjectInspector(PrimitiveObjectInspectorFactory
                .getPrimitiveWritableObjectInspector(PrimitiveObjectInspectorUtils
                        .getTypeEntryFromPrimitiveWritableClass(c).primitiveCategory));
    }

    Field[] fields = ObjectInspectorUtils.getDeclaredNonStaticFields(c);
    ArrayList<String> fieldNames = new ArrayList<String>(fields.length);
    ArrayList<TypeInfo> fieldTypeInfos = new ArrayList<TypeInfo>(fields.length);
    for (int i = 0; i < fields.length; i++) {
        fieldNames.add(fields[i].getName());
        fieldTypeInfos.add(getExtendedTypeInfoFromJavaType(fields[i].getGenericType(), m));
    }
    return TypeInfoFactory.getStructTypeInfo(fieldNames, fieldTypeInfos);
}

From source file:org.jiemamy.utils.reflect.GenericUtil.java

/**
 * {@code type}???//from   ww  w  . j a  v  a2  s. c  om
 * <ul>
 * <li>{@code type}?{@code Class}?????????</li>
 * <li>{@code type}??????????</li>
 * <li>{@code type}????(??)??</li>
 * <li>{@code type}??????????????</li>
 * <li>??????{@code null}?</li>
 * </ul>
 * 
 * @param type 
 * @return {@code type}?
 * @throws IllegalArgumentException ?{@code null}???
 */
public static Class<?> getRawClass(Type type) {
    Validate.notNull(type);
    if (Class.class.isInstance(type)) {
        return Class.class.cast(type);
    }
    if (ParameterizedType.class.isInstance(type)) {
        ParameterizedType parameterizedType = ParameterizedType.class.cast(type);
        return getRawClass(parameterizedType.getRawType());
    }
    if (WildcardType.class.isInstance(type)) {
        WildcardType wildcardType = WildcardType.class.cast(type);
        Type[] types = wildcardType.getUpperBounds();
        return getRawClass(types[0]);
    }
    if (GenericArrayType.class.isInstance(type)) {
        GenericArrayType genericArrayType = GenericArrayType.class.cast(type);
        Class<?> rawClass = getRawClass(genericArrayType.getGenericComponentType());
        return Array.newInstance(rawClass, 0).getClass();
    }
    return null;
}

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

private static void extractTypeVariablesFromGenericInterfaces(Type[] genericInterfaces,
        Map<TypeVariable, Type> typeVariableMap) {
    for (Type genericInterface : genericInterfaces) {
        if (genericInterface instanceof ParameterizedType) {
            ParameterizedType pt = (ParameterizedType) genericInterface;
            populateTypeMapFromParameterizedType(pt, typeVariableMap);
            if (pt.getRawType() instanceof Class) {
                extractTypeVariablesFromGenericInterfaces(((Class) pt.getRawType()).getGenericInterfaces(),
                        typeVariableMap);
            }/*  w ww. j  a v a  2s .  co  m*/
        } else if (genericInterface instanceof Class) {
            extractTypeVariablesFromGenericInterfaces(((Class) genericInterface).getGenericInterfaces(),
                    typeVariableMap);
        }
    }
}

From source file:org.jiemamy.utils.reflect.GenericUtil.java

/**
 * ??(???)??????? {@code map}??/*www  .  ja va 2s .c om*/
 * 
 * @param type 
 * @param map ????????{@link Map}
 * @throws IllegalArgumentException ?{@code null}???
 */
protected static void gatherTypeVariables(Type type, Map<TypeVariable<?>, Type> map) {
    Validate.notNull(type);
    Validate.notNull(map);
    if (ParameterizedType.class.isInstance(type)) {
        ParameterizedType parameterizedType = ParameterizedType.class.cast(type);
        TypeVariable<?>[] typeVariables = GenericDeclaration.class.cast(parameterizedType.getRawType())
                .getTypeParameters();
        Type[] actualTypes = parameterizedType.getActualTypeArguments();
        for (int i = 0; i < actualTypes.length; ++i) {
            map.put(typeVariables[i], actualTypes[i]);
        }
    }
}