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:ReflectUtil.java

/**
 * Returns an array of Type objects representing the actual type arguments
 * to targetType used by clazz.//from ww w. ja v  a2s .  co  m
 * 
 * @param clazz the implementing class (or subclass)
 * @param targetType the implemented generic class or interface
 * @return an array of Type objects or null
 */
public static Type[] getActualTypeArguments(Class<?> clazz, Class<?> targetType) {
    Set<Class<?>> classes = new HashSet<Class<?>>();
    classes.add(clazz);

    if (targetType.isInterface())
        classes.addAll(getImplementedInterfaces(clazz));

    Class<?> superClass = clazz.getSuperclass();
    while (superClass != null) {
        classes.add(superClass);
        superClass = superClass.getSuperclass();
    }

    for (Class<?> search : classes) {
        for (Type type : (targetType.isInterface() ? search.getGenericInterfaces()
                : new Type[] { search.getGenericSuperclass() })) {
            if (type instanceof ParameterizedType) {
                ParameterizedType parameterizedType = (ParameterizedType) type;
                if (targetType.equals(parameterizedType.getRawType()))
                    return parameterizedType.getActualTypeArguments();
            }
        }
    }

    return null;
}

From source file:org.evosuite.utils.generic.GenericUtils.java

/**
 * TODO: Try to match p2 superclasses? /* w w  w  .j  a v a 2s .  com*/
 * 
 * @param p1 Desired TypeVariable assignment
 * @param p2 Generic type with the TypeVariables that need assignment
 * @return
 */
public static Map<TypeVariable<?>, Type> getMatchingTypeParameters(ParameterizedType p1, ParameterizedType p2) {
    logger.debug("Matching generic types between " + p1 + " and " + p2);
    Map<TypeVariable<?>, Type> map = new HashMap<TypeVariable<?>, Type>();
    if (!p1.getRawType().equals(p2.getRawType())) {
        logger.debug("Raw types do not match!");

        GenericClass ownerClass = new GenericClass(p2);

        if (GenericClass.isSubclass(p1.getRawType(), p2.getRawType())) {
            logger.debug(p1 + " is a super type of " + p2);
            Map<TypeVariable<?>, Type> commonsMap = TypeUtils.determineTypeArguments((Class<?>) p2.getRawType(),
                    p1);
            logger.debug("Adding to map: " + commonsMap);
            // TODO: Now we would need to iterate over the type parameters, and update the map?
            //map.putAll(commonsMap);

            for (TypeVariable<?> t : map.keySet()) {
                logger.debug(t + ": " + t.getGenericDeclaration());
            }

            // For each type variable of the raw type, map the parameter type to that type
            Type[] p2TypesA = ((Class<?>) p2.getRawType()).getTypeParameters();
            Type[] p2TypesB = p2.getActualTypeArguments();
            for (int i = 0; i < p2TypesA.length; i++) {
                Type a = p2TypesA[i];
                Type b = p2TypesB[i];
                logger.debug("Should be mapping " + a + " and " + b);
                if (a instanceof TypeVariable<?>) {
                    logger.debug(a + " is a type variable: " + ((TypeVariable<?>) a).getGenericDeclaration());
                    if (b instanceof TypeVariable<?>) {
                        logger.debug(
                                b + " is a type variable: " + ((TypeVariable<?>) b).getGenericDeclaration());
                        if (commonsMap.containsKey((TypeVariable<?>) a)
                                && !(commonsMap.get((TypeVariable<?>) a) instanceof WildcardType)
                                && !(commonsMap.get((TypeVariable<?>) a) instanceof TypeVariable<?>))
                            map.put((TypeVariable<?>) b, commonsMap.get((TypeVariable<?>) a));
                        //else
                        //   map.put((TypeVariable<?>)a, b);
                    }
                }

                //               if(b instanceof TypeVariable<?>) {
                //                  if(map.containsKey(a))
                //                     map.put((TypeVariable<?>)b, map.get(a));
                //                  //else
                //                  //   map.put((TypeVariable<?>)b, a);
                //               }

                logger.debug("Updated map: " + map);
            }

        }

        for (GenericClass interfaceClass : ownerClass.getInterfaces()) {
            if (interfaceClass.isParameterizedType())
                map.putAll(getMatchingTypeParameters(p1, (ParameterizedType) interfaceClass.getType()));
            else
                logger.debug("Interface " + interfaceClass + " is not parameterized");
        }
        if (ownerClass.getRawClass().getSuperclass() != null) {
            GenericClass ownerSuperClass = ownerClass.getSuperClass();
            if (ownerSuperClass.isParameterizedType())
                map.putAll(getMatchingTypeParameters(p1, (ParameterizedType) ownerSuperClass.getType()));
            else
                logger.debug("Super type " + ownerSuperClass + " is not parameterized");
        }
        return map;
    }

    for (int i = 0; i < p1.getActualTypeArguments().length; i++) {
        Type t1 = p1.getActualTypeArguments()[i];
        Type t2 = p2.getActualTypeArguments()[i];
        if (t1 == t2)
            continue;
        logger.debug("First match: " + t1 + " - " + t2);
        if (t1 instanceof TypeVariable<?>) {
            map.put((TypeVariable<?>) t1, t2);
        }
        if (t2 instanceof TypeVariable<?>) {
            map.put((TypeVariable<?>) t2, t1);
        } else if (t2 instanceof ParameterizedType && t1 instanceof ParameterizedType) {
            map.putAll(getMatchingTypeParameters((ParameterizedType) t1, (ParameterizedType) t2));
        }
        logger.debug("Updated map: " + map);

    }

    if (p1.getOwnerType() != null && p1.getOwnerType() instanceof ParameterizedType
            && p2.getOwnerType() instanceof ParameterizedType) {
        map.putAll(getMatchingTypeParameters((ParameterizedType) p1.getOwnerType(),
                (ParameterizedType) p2.getOwnerType()));
    }

    return map;
}

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

/**
 * Returns the FieldDefinition for a field of the specified type.
 * /*from w w  w .  j a  va2 s .  c  om*/
 * @param type
 * @param typeState
 * @param strict True if strict mode is on; not enough information will result in exceptions instead of warnings.
 * @param The name of this field (if known)
 * @return The corresponding fieldDefinition to the type.
 */
public static FieldDefinition getFieldDefinition(Type type, TypeState typeState, boolean strict, String name) {

    GenericFieldDefinition ret = new GenericFieldDefinition();
    ret.setName(name);

    if (type == null) {
        // do nothing, it's null, but do return a FieldDefinition
    } else if (type instanceof Class) {
        Class<?> returnTypeClass = (Class<?>) type;

        if (returnTypeClass.isArray()) {
            Tuple.Two<TypeDefinition, List<ListTypeDefinition>> dimAndClass = getArrayDimensions(
                    returnTypeClass, typeState, strict);
            ret.setTypeDefinition(dimAndClass.v1);
            ret.setArrayTypes(dimAndClass.v2);
        } else if (!strict && Collection.class.isAssignableFrom(returnTypeClass)) {
            if (!JSON.class.isAssignableFrom(returnTypeClass)) {
                logger.warn(MessageResource.JSON_TYPE_NOGENERICS.getMessage(returnTypeClass));
            }

            ret.setArrayTypes(new ArrayList<ListTypeDefinition>(1));
            ret.getArrayTypes().add(getListTypeDefinition(returnTypeClass, typeState, strict));
        } else if (ClassUtils.isPrimitiveOrWrapper(returnTypeClass)) {
            TypeDefinition td = getTypeDefinition(returnTypeClass, typeState, strict);
            ret.setTypeDefinition(td);
        } else {
            TypeDefinition td = getTypeDefinition(returnTypeClass, typeState, strict);
            ret.setTypeDefinition(td);
        }
    } else if (type instanceof ParameterizedType) {
        ParameterizedType pt = (ParameterizedType) type;

        if (Class.class == pt.getRawType()) {
            TypeDefinition td = getTypeDefinition(Class.class, typeState, strict);
            ret.setTypeDefinition(td);
        } else if (pt.getRawType() instanceof Class
                && Collection.class.isAssignableFrom((Class<?>) pt.getRawType())) {
            Tuple.Two<TypeDefinition, List<ListTypeDefinition>> dimAndClass = getArrayDimensions(pt, typeState,
                    strict);
            ret.setTypeDefinition(dimAndClass.v1);
            ret.setArrayTypes(dimAndClass.v2);
        } else if (pt.getRawType() instanceof Class && Map.class.isAssignableFrom((Class<?>) pt.getRawType())) {
            TypeDefinition td = getTypeDefinition(pt, typeState, strict);
            ret.setTypeDefinition(td);
        } else {
            if (strict) {
                throw new WMRuntimeException(MessageResource.JSON_TYPE_UNKNOWNRAWTYPE, pt.getOwnerType(), pt);
            } else {
                logger.warn(MessageResource.JSON_TYPE_UNKNOWNRAWTYPE.getMessage(pt.getOwnerType(), pt));
            }
        }
    } else if (type instanceof GenericArrayType) {
        Tuple.Two<TypeDefinition, List<ListTypeDefinition>> dimAndClass = getArrayDimensions(type, typeState,
                strict);
        ret.setTypeDefinition(dimAndClass.v1);
        ret.setArrayTypes(dimAndClass.v2);
    } else {
        throw new WMRuntimeException(MessageResource.JSON_TYPE_UNKNOWNPARAMTYPE, type,
                type != null ? type.getClass() : null);
    }

    return ret;
}

From source file:reflex.node.KernelExecutor.java

private static Object handleParameterizedType(ReflexValue v, Type type) {
    if (!(type instanceof ParameterizedType)) {
        if (type.equals(String.class))
            return v.asString();
        if (type.equals(Double.class))
            return v.asDouble();
        if (type.equals(Long.class))
            return v.asLong();
        if (type.equals(BigDecimal.class))
            return v.asBigDecimal();
        return v.asObject();
    }//from w  w  w.  j a v a2s  .  co m

    ParameterizedType pType = (ParameterizedType) type;
    if (pType.getRawType().equals(Map.class)) {
        if (!v.isMap()) {
            log.error(v.toString() + " is not a map");
            return null;
        }
        Map<String, Object> convertedMap = new LinkedHashMap<>();

        for (Entry<String, Object> entry : v.asMap().entrySet()) {
            Type[] innerType = pType.getActualTypeArguments();
            String key = null;
            if (!innerType[0].equals(String.class)) {
                // This could get tricky
                log.warn("Keys for maps should always be Strings");
            }
            key = entry.getKey().toString();
            Object value = entry.getValue();
            if (value instanceof ReflexValue)
                convertedMap.put(key, handleParameterizedType((ReflexValue) value, innerType[1]));
            else
                convertedMap.put(key, value);
        }
        return convertedMap;
    } else if (pType.getRawType().equals(List.class)) {
        if (!v.isList()) {
            log.error(v.toString() + " is not a list");
            return null;
        }
        List<ReflexValue> inner = v.asList();
        Type innerType = pType.getActualTypeArguments()[0];
        if (innerType.equals(String.class)) {
            List<String> ret = new ArrayList<String>(inner.size());
            for (ReflexValue vi : inner) {
                ret.add(vi.asString());
            }
            return ret;
        } else if (innerType.equals(Double.class)) {
            List<Double> ret = new ArrayList<>(inner.size());
            for (ReflexValue vi : inner) {
                ret.add(vi.asDouble());
            }
            return ret;
        } else if (innerType.equals(Long.class)) {
            List<Long> ret = new ArrayList<>(inner.size());
            for (ReflexValue vi : inner) {
                ret.add(vi.asLong());
            }
            return ret;
        } else if (innerType.equals(BigDecimal.class)) {
            List<BigDecimal> ret = new ArrayList<>(inner.size());
            for (ReflexValue vi : inner) {
                ret.add(vi.asBigDecimal());
            }
            return ret;
        } else if (innerType instanceof ParameterizedType || inner instanceof List) {
            List<Object> ret = new ArrayList<>();
            for (ReflexValue vi : inner) {
                ret.add(handleParameterizedType(vi, innerType));
            }
            return ret;
        } else {
            log.warn("Cannot convert " + v.toString() + " to " + type.toString());
        }
    } else if (v.isMap()) {
        // If it's a map then JacksonUtil may be able to recreate the type
        return handleMap(v, type);
    }
    return v.asObject();
}

From source file:org.wso2.msf4j.internal.router.ParamConvertUtils.java

/**
 * Creates a converter function that converts form parameter into an object of the given result type.
 * It follows the supported types of {@link org.wso2.msf4j.formparam.FormDataParam} with the following exceptions:
 * <ol>/*from  ww w  .  j a  va  2s . c om*/
 * <li>Does not support types registered with {@link javax.ws.rs.ext.ParamConverterProvider}</li>
 * </ol>
 *
 * @param resultType Result type
 * @return Function the function
 */
public static Function<List<String>, Object> createFormDataParamConverter(Type resultType) {
    // For java.io.File we only support List ParameterizedType
    if (resultType instanceof ParameterizedType) {
        ParameterizedType type = (ParameterizedType) resultType;
        Type elementType = type.getActualTypeArguments()[0];
        if (elementType == File.class && type.getRawType() != List.class) {
            throw new IllegalArgumentException("Unsupported type " + resultType);
        }
    }
    Function<List<String>, Object> listConverter = null;
    try {
        listConverter = createListConverter(resultType);
    } catch (Throwable e) {
        // Ignore the exceptions since from the logic we will handle the beans and Files
    }
    return listConverter;
}

From source file:com.initialxy.cordova.themeablebrowser.ThemeableBrowserUnmarshaller.java

/**
 * Given an JSONArray retrieved from JSONObject, and the destination item
 * type, unmarshall this list to a List of given item type.
 *
 * @param jsonArr/*  ww  w . j  a  v a2  s.  c  o  m*/
 * @param itemType
 * @return
 */
private static List<?> JSONToList(JSONArray jsonArr, Type itemType) {
    List<Object> result = new ArrayList<Object>();

    Class<?> rawType = null;
    ParameterizedType pType = null;

    if (itemType instanceof ParameterizedType) {
        pType = (ParameterizedType) itemType;
        rawType = (Class<?>) pType.getRawType();
    } else {
        rawType = (Class<?>) itemType;
    }

    int len = jsonArr.length();
    for (int i = 0; i < len; i++) {
        try {
            Object item = jsonArr.get(i);
            Object converted = valToType(item, itemType);
            if (converted != null) {
                result.add(converted);
            }
        } catch (JSONException e) {
            throw new ParserException(e);
        }
    }

    return result;
}

From source file:org.eiichiro.bootleg.Types.java

/**
 * Returns the raw type of the specified type.
 * This method supports {@code ParameterizedType} or raw {@code Class} 
 * (just returns it directly). The other types such as array type are not 
 * supported. If the specified 'type' is not supported, this method returns 
 * <code>null</code>.//w  w w  . j a v a  2  s. c o  m
 * 
 * @param type The type to be tested.
 * @return The raw type of the specified type.
 */
public static Class<?> getRawType(Type type) {
    if (type instanceof ParameterizedType) {
        ParameterizedType parameterizedType = (ParameterizedType) type;
        return (Class<?>) parameterizedType.getRawType();
    } else if (type instanceof Class<?>) {
        Class<?> clazz = (Class<?>) type;
        return (clazz.isArray()) ? null : clazz;
    } else {
        return null;
    }
}

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

private static Class[] doResolveTypeArguments(Class ownerClass, Type ifc, Class genericIfc) {
    if (ifc instanceof ParameterizedType) {
        ParameterizedType paramIfc = (ParameterizedType) ifc;
        Type rawType = paramIfc.getRawType();
        if (genericIfc.equals(rawType)) {
            Type[] typeArgs = paramIfc.getActualTypeArguments();
            Class[] result = new Class[typeArgs.length];
            for (int i = 0; i < typeArgs.length; i++) {
                Type arg = typeArgs[i];
                result[i] = extractClass(ownerClass, arg);
            }//from ww w. j  a v a  2s .co m
            return result;
        } else if (genericIfc.isAssignableFrom((Class) rawType)) {
            return doResolveTypeArguments(ownerClass, (Class) rawType, genericIfc);
        }
    } else if (ifc != null && genericIfc.isAssignableFrom((Class) ifc)) {
        return doResolveTypeArguments(ownerClass, (Class) ifc, genericIfc);
    }
    return null;
}

From source file:net.radai.beanz.util.ReflectionUtil.java

public static String prettyPrint(Type type) {
    if (type instanceof GenericArrayType) {
        GenericArrayType genericArrayType = (GenericArrayType) type;
        return prettyPrint(genericArrayType.getGenericComponentType()) + "[]";
    }//from w  w  w  .j a v a  2 s .  c o  m
    if (type instanceof WildcardType) {
        WildcardType wildcardType = (WildcardType) type;
        return wildcardType.toString();
    }
    if (type instanceof TypeVariable) {
        TypeVariable<?> typeVariable = (TypeVariable) type;
        return typeVariable.getName();
    }
    if (type instanceof ParameterizedType) {
        ParameterizedType parameterizedType = (ParameterizedType) type;
        StringBuilder sb = new StringBuilder();
        sb.append(prettyPrint(parameterizedType.getRawType()));
        Type[] typeArguments = parameterizedType.getActualTypeArguments();
        if (typeArguments != null && typeArguments.length > 0) {
            sb.append("<");
            for (Type typeArgument : typeArguments) {
                sb.append(prettyPrint(typeArgument)).append(", ");
            }
            sb.delete(sb.length() - 2, sb.length()); // last ", "
            sb.append(">");
        }
        return sb.toString();
    }
    Class<?> clazz = (Class<?>) type;
    if (clazz.isArray()) {
        return prettyPrint(clazz.getComponentType()) + "[]";
    }
    return clazz.getSimpleName();
}

From source file:com.googlecode.android_scripting.rpc.MethodDescriptor.java

/**
 * Appends the name of the given type to the {@link StringBuilder}.
 * //from ww w.  ja va  2  s . c o  m
 * @param builder
 *          string builder to append to
 * @param type
 *          type whose name to append
 */
private static void appendTypeName(final StringBuilder builder, final Type type) {
    if (type instanceof Class<?>) {
        builder.append(((Class<?>) type).getSimpleName());
    } else {
        ParameterizedType parametrizedType = (ParameterizedType) type;
        builder.append(((Class<?>) parametrizedType.getRawType()).getSimpleName());
        builder.append("<");

        Type[] arguments = parametrizedType.getActualTypeArguments();
        for (int i = 0; i < arguments.length; i++) {
            if (i > 0) {
                builder.append(", ");
            }
            appendTypeName(builder, arguments[i]);
        }
        builder.append(">");
    }
}