private Object convert( Type targetType, Object sourceObject, Action<? super SourceObjectMapping> mapping) { if (targetType instanceof ParameterizedType) { ParameterizedType parameterizedTargetType = (ParameterizedType) targetType; if (parameterizedTargetType.getRawType() instanceof Class) { Class<?> rawClass = (Class<?>) parameterizedTargetType.getRawType(); if (Iterable.class.isAssignableFrom(rawClass)) { Type targetElementType = getElementType(parameterizedTargetType, 0); return convertCollectionInternal( rawClass, targetElementType, (Iterable<?>) sourceObject, mapping); } if (Map.class.isAssignableFrom(rawClass)) { Type targetKeyType = getElementType(parameterizedTargetType, 0); Type targetValueType = getElementType(parameterizedTargetType, 1); return convertMap( rawClass, targetKeyType, targetValueType, (Map<?, ?>) sourceObject, mapping); } } } if (targetType instanceof Class) { if (((Class) targetType).isPrimitive()) { return sourceObject; } return adapt((Class) targetType, sourceObject, mapping); } throw new UnsupportedOperationException( String.format("Cannot convert object of %s to %s.", sourceObject.getClass(), targetType)); }
/** * @param type - something like List<T>, List<T extends Number> * @param containingType - the shallowest type in the hierarchy where type is defined. * @return the passed type if nothing to resolve or a copy of the type with the type arguments * resolved. */ private static ParameterizedType resolve(ParameterizedType type, Type containingType) { // Use a copy because we're going to modify it. final Type[] types = type.getActualTypeArguments().clone(); boolean modified = resolve(types, containingType); return modified ? create(type.getRawType(), type.getOwnerType(), types) : type; }
static Class<?> resultType(Method finderMethod) { checkArgument(finderMethod.getReturnType() == Iterator.class); Type t = finderMethod.getGenericReturnType(); ParameterizedType pt = (ParameterizedType) t; Type r = pt.getActualTypeArguments()[0]; return (Class<?>) r; }
private static int checkParameterizedType( String subroutineName, ParameterizedType expectedType, ArgumentsList arguments, List<LispObject> args, int argsCounter, int i) { Type rawType = expectedType.getRawType(); Type expectedTypeArguments = expectedType.getActualTypeArguments()[0]; try { if (((Class) rawType).isInstance(args.get(argsCounter))) { Type actualTypeArguments = ((ParameterizedType) (Type) args.get(argsCounter).getClass()) .getActualTypeArguments()[0]; if (!expectedTypeArguments.equals(actualTypeArguments)) { throw new WrongTypeArgumentException( ((Class) rawType).getSimpleName() + "<" + ((Class) expectedTypeArguments).getSimpleName() + ">", args.get(argsCounter)); } arguments.setValue(i, args.get(argsCounter)); return argsCounter + 1; } else { if (arguments.isOptional(i)) return -1; throw new WrongTypeArgumentException(expectedType.toString(), args.get(argsCounter)); } } catch (IndexOutOfBoundsException e) { if (arguments.isOptional(i)) return -1; throw new WrongNumberOfArgumentsException(subroutineName, i); } }
static Class<?> getTypeClass(Type type) { if (type instanceof Class<?>) { return (Class<?>) type; } if (type instanceof ParameterizedType) { ParameterizedType pt = (ParameterizedType) type; Class<?> c = (Class<?>) pt.getRawType(); if (ValuedEnum.class.isAssignableFrom(c)) { Type[] types = pt.getActualTypeArguments(); if (types == null || types.length != 1) { c = int.class; } else { c = getTypeClass(pt.getActualTypeArguments()[0]); } } return c; } if (type instanceof GenericArrayType) { if (Object.class.isAssignableFrom( getTypeClass(((GenericArrayType) type).getGenericComponentType()))) { return Object[].class; } } throw new UnsupportedOperationException("Unknown type type : " + type.getClass().getName()); }
@Nullable private static TypeWrapper wrap(Type type) { if (type == null) { return null; } else if (type instanceof Class) { return new ClassTypeWrapper((Class<?>) type); } else if (type instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType) type; return new ParameterizedTypeWrapper( toWrappers(parameterizedType.getActualTypeArguments()), (ClassTypeWrapper) wrap(parameterizedType.getRawType()), wrap(parameterizedType.getOwnerType())); } else if (type instanceof WildcardType) { WildcardType wildcardType = (WildcardType) type; return new WildcardTypeWrapper( toWrappers(wildcardType.getUpperBounds()), toWrappers(wildcardType.getLowerBounds()), type.hashCode()); } else if (type instanceof TypeVariable) { TypeVariable<?> typeVariable = (TypeVariable<?>) type; return new TypeVariableTypeWrapper( typeVariable.getName(), toWrappers(typeVariable.getBounds()), type.hashCode()); } else if (type instanceof GenericArrayType) { GenericArrayType genericArrayType = (GenericArrayType) type; return new GenericArrayTypeWrapper( wrap(genericArrayType.getGenericComponentType()), type.hashCode()); } else { throw new IllegalArgumentException("cannot wrap type of type " + type.getClass()); } }
private boolean argsEquivalent(ParameterizedType ancestor) { for (int i = 0; i < ancestor.typeArguments().size(); i++) { Type arg1 = (Type) ancestor.typeArguments().get(i); Type arg2 = (Type) typeArguments().get(i); IntersectionType cap1 = (IntersectionType) ancestor.typeVariables().get(i); IntersectionType cap2 = (IntersectionType) baseType().typeVariables().get(i); // if both are AnySubType then arg2 bound must be subtype // of arg1 bound if (arg1 instanceof AnySubType) { if (arg2 instanceof AnySubType) { if (!typeSystem().equals(((AnySubType) arg2).bound(), ((AnySubType) arg1).bound())) return false; } else if (arg2 instanceof AnySuperType) { if (!typeSystem().equals(((AnySubType) arg1).bound(), ((AnySuperType) arg2).bound())) return false; } else if (arg2 instanceof IntersectionType) { // need to break out here or will recurse for ever if (((IntersectionType) arg2) .name() .equals(((IntersectionType) ((AnySubType) arg1).bound()).name())) return true; } // if only ancestor(arg1) is AnySubType then arg2 is not // wildcard must be subtype of bound of arg1 else { if (!typeSystem().equals(arg2, arg1)) return false; } } // if both are AnySuperType then arg1 bound must be a subtype // of arg2 bound else if (arg1 instanceof AnySuperType) { if (arg2 instanceof AnySuperType) { if (!typeSystem().equals(((AnySuperType) arg1).bound(), ((AnySuperType) arg2).bound())) return false; } // if only arg1 instanceof AnySuperType then arg1 bounds // must be a subtype of arg2 else { if (!typeSystem().equals(arg1, arg2)) return false; } } else if (arg1 instanceof AnyType) { if (arg2 instanceof AnyType) { if (!typeSystem().equals(((AnyType) arg1).upperBound(), ((AnyType) arg2).upperBound())) return false; } else { if (!typeSystem().equals(arg1, arg2)) return false; } } else if (arg1 instanceof ParameterizedType && arg2 instanceof ParameterizedType) { // if (arg1.equals(arg2)) return true; if (!typeSystem().equals(arg1, arg2)) return false; } else if (arg1 instanceof IntersectionType && arg2 instanceof IntersectionType) { if (!typeSystem().equals(arg1, arg2) && !((JL5TypeSystem) typeSystem()).isEquivalent(arg1, arg2)) return false; } else { if (!typeSystem().equals(arg1, arg2)) return false; } } return true; }
@Test public void get_generic_type_of_a_field() throws Exception { Field field = Dummy.class.getDeclaredField("stringListField"); ParameterizedType type = (ParameterizedType) field.getGenericType(); assertEquals(List.class, type.getRawType()); assertArrayEquals(new Type[] {String.class}, type.getActualTypeArguments()); assertEquals(null, type.getOwnerType()); }
/** * Returns the generic type information of an attribute. * * @param field the field representation of the attribute. * @return an array of types that are used to parameterize the attribute. */ public static Class<?>[] getGenericTypes(Field field) { Type genericFieldType = field.getGenericType(); if (!(genericFieldType instanceof ParameterizedType)) return null; // type is not generic ParameterizedType pType = (ParameterizedType) genericFieldType; Type[] args = pType.getActualTypeArguments(); Class<?>[] types = new Class[args.length]; System.arraycopy(args, 0, types, 0, args.length); return types; }
@Test public void get_generic_type_of_interface_method_parameters() throws Exception { Method method = Interface.class.getDeclaredMethod("stringListMethod", List.class); Type[] types = method.getGenericParameterTypes(); ParameterizedType type = (ParameterizedType) types[0]; assertEquals(List.class, type.getRawType()); assertArrayEquals(new Type[] {String.class}, type.getActualTypeArguments()); assertEquals(null, type.getOwnerType()); }
public static <T> Class<T> tellMeTheTypeOfThisThing() throws NoSuchMethodException { Method method = InferGenericTypeForAStaticMethodTest.class.getDeclaredMethod( "tellMeTheTypeOfThisThing", null); ParameterizedType type = (ParameterizedType) method.getGenericReturnType(); TypeVariableImpl typeImpl = (TypeVariableImpl) type.getActualTypeArguments()[0]; System.out.println(typeImpl); return null; }
public ULongType() { super( x10.core.ULong.class, new Type[] { ParameterizedType.make(Types.COMPARABLE, UnresolvedType.THIS), ParameterizedType.make(x10.lang.Arithmetic.$RTT, UnresolvedType.THIS), ParameterizedType.make(x10.lang.Bitwise.$RTT, UnresolvedType.THIS), ParameterizedType.make(x10.util.Ordered.$RTT, UnresolvedType.THIS), Types.STRUCT }); }
private void visitType(java.lang.reflect.Type type, StringBuilder builder) { if (type instanceof Class) { Class<?> cl = (Class<?>) type; if (cl.isPrimitive()) { builder.append(Type.getType(cl).getDescriptor()); } else { if (cl.isArray()) { builder.append(cl.getName().replace('.', '/')); } else { builder.append('L'); builder.append(cl.getName().replace('.', '/')); builder.append(';'); } } } else if (type instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType) type; visitNested(parameterizedType.getRawType(), builder); builder.append('<'); for (java.lang.reflect.Type param : parameterizedType.getActualTypeArguments()) { visitType(param, builder); } builder.append(">;"); } else if (type instanceof WildcardType) { WildcardType wildcardType = (WildcardType) type; if (wildcardType.getUpperBounds().length == 1 && wildcardType.getUpperBounds()[0].equals(Object.class)) { if (wildcardType.getLowerBounds().length == 0) { builder.append('*'); return; } } else { for (java.lang.reflect.Type upperType : wildcardType.getUpperBounds()) { builder.append('+'); visitType(upperType, builder); } } for (java.lang.reflect.Type lowerType : wildcardType.getLowerBounds()) { builder.append('-'); visitType(lowerType, builder); } } else if (type instanceof TypeVariable) { TypeVariable<?> typeVar = (TypeVariable) type; builder.append('T'); builder.append(typeVar.getName()); builder.append(';'); } else if (type instanceof GenericArrayType) { GenericArrayType arrayType = (GenericArrayType) type; builder.append('['); visitType(arrayType.getGenericComponentType(), builder); } else { throw new IllegalArgumentException( String.format("Cannot generate signature for %s.", type)); } }
/* * @see ASTVisitor#visit(ParameterizedType) * @since 3.0 */ @Override public boolean visit(ParameterizedType node) { node.getType().accept(this); this.fBuffer.append("<"); // $NON-NLS-1$ for (Iterator<Type> it = node.typeArguments().iterator(); it.hasNext(); ) { Type t = it.next(); t.accept(this); if (it.hasNext()) { this.fBuffer.append(","); // $NON-NLS-1$ } } this.fBuffer.append(">"); // $NON-NLS-1$ return false; }
private Object replace(Class<?> type, ApplicableGenerator generator, boolean alternative) { for (Creator<?> creator : creators) { ParameterizedType generic = (ParameterizedType) creator.getClass().getGenericInterfaces()[0]; Class<?> restrained = generic.getActualTypeArguments()[0] instanceof ParameterizedType ? (Class<?>) ((ParameterizedType) generic.getActualTypeArguments()[0]).getRawType() : (Class<?>) generic.getActualTypeArguments()[0]; if (type.isAssignableFrom(restrained)) { return creator.create(); } } return generator.generate(type, alternative); }
private Object generate(Class<?> type, boolean alternative) { for (Generator<?> generator : generators) { ParameterizedType generic = (ParameterizedType) generator.getClass().getGenericInterfaces()[0]; Class<?> restrained = generic.getActualTypeArguments()[0] instanceof ParameterizedType ? (Class<?>) ((ParameterizedType) generic.getActualTypeArguments()[0]).getRawType() : (Class<?>) generic.getActualTypeArguments()[0]; if (type.isAssignableFrom(restrained)) { type = generator.generate(); } } return type == String.class ? alternative ? OTHER_STRING : DEFAULT_STRING : mock(type); }
@SuppressWarnings("unchecked") private void apply(Object mock) { for (Refinement refinement : refinements) { ParameterizedType generic = (ParameterizedType) refinement.getClass().getGenericInterfaces()[0]; Class<?> restrained = generic.getActualTypeArguments()[0] instanceof ParameterizedType ? (Class<?>) ((ParameterizedType) generic.getActualTypeArguments()[0]).getRawType() : (Class<?>) generic.getActualTypeArguments()[0]; if (restrained.isInstance(mock)) { refinement.apply(mock); } } }
/** * Gets the type of a parameterized List * * @param scope * @return */ public Class getParameterizedListType(Scope scope) { Type returnType = method.getGenericReturnType(); ParameterizedType type = (ParameterizedType) returnType; Type[] typeArguments = type.getActualTypeArguments(); Class typeArgClass = (Class) typeArguments[0]; // System.out.println("typeArgClass = " + typeArgClass); return typeArgClass; /* * Class rtnType = method.getReturnType(); TypeVariable[] typeParam = * rtnType.getTypeParameters(); Class listType = typeParam[0].getClass(); * return ClassUtil.getObjectClass(listType); */ }
/** * Compute the erasure of a type. * * @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(); } }
private Class<?> resolveReturnType(Method me) { Type returnType = me.getGenericReturnType(); if (returnType instanceof ParameterizedType) { ParameterizedType type = (ParameterizedType) returnType; Type[] typeArguments = type.getActualTypeArguments(); for (Type typeArgument : typeArguments) { if (typeArgument instanceof Class<?>) { return (Class<?>) typeArgument; } } return null; } return (Class<?>) returnType; }
private ReferenceTypeUsage toReferenceTypeUsage(Class<?> clazz, Type type) { TypeDefinition typeDefinition = new ReflectionBasedTypeDefinition(clazz); ReferenceTypeUsage referenceTypeUsage = new ReferenceTypeUsage(typeDefinition); if (type instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType) type; for (int tp = 0; tp < clazz.getTypeParameters().length; tp++) { TypeVariable<? extends Class<?>> typeVariable = clazz.getTypeParameters()[tp]; Type parameterType = parameterizedType.getActualTypeArguments()[tp]; referenceTypeUsage .getTypeParameterValues() .add(typeVariable.getName(), toTypeUsage(parameterType)); } } return referenceTypeUsage; }
public static <C, I> Type[] getGenericInterfaceParams( Class<C> checkedClass, Class<I> searchedInterface) { for (Type type : checkedClass.getGenericInterfaces()) { ParameterizedType pt = (ParameterizedType) type; if (searchedInterface.equals(pt.getRawType())) { ParameterizedType pType = ((ParameterizedType) type); return pType.getActualTypeArguments(); } } if (!Object.class.equals(checkedClass.getSuperclass())) return getGenericInterfaceParams(checkedClass.getSuperclass(), searchedInterface); throw new ConfigurationError( checkedClass + " does not implement interface with generic parameters: " + searchedInterface); }
public boolean isAssignableTo(Type<?> superType) { if (this == superType) return true; if (superType == Types.ANY) return true; if (superType instanceof RuntimeType<?>) { RuntimeType<?> rt = (RuntimeType<?>) superType; if (rt.javaClass.isAssignableFrom(javaClass)) { return true; } } if (superType instanceof ParameterizedType) { ParameterizedType<?> pt = (ParameterizedType<?>) superType; if (pt.getRawType().isAssignableFrom(pt.getActualTypeArguments(), this, null)) { return true; } } return false; }
private Type getElementType(ParameterizedType type, int index) { Type elementType = type.getActualTypeArguments()[index]; if (elementType instanceof WildcardType) { WildcardType wildcardType = (WildcardType) elementType; return wildcardType.getUpperBounds()[0]; } return elementType; }
@Override public boolean visit(VariableDeclarationStatement node) { Type typ = node.getType(); if (typ.isSimpleType()) { SimpleType simple = (SimpleType) typ; String typName = simple.getName().getFullyQualifiedName(); List<VariableDeclarationFragment> vars = node.fragments(); for (VariableDeclarationFragment var : vars) { map.put(var.getName().getIdentifier(), typName); } } if (typ.isQualifiedType()) { QualifiedType qual = (QualifiedType) typ; String typName = qual.getName().getFullyQualifiedName(); List<VariableDeclarationFragment> vars = node.fragments(); for (VariableDeclarationFragment var : vars) { map.put(var.getName().getIdentifier(), typName); } } if (typ.isPrimitiveType()) { PrimitiveType prim = (PrimitiveType) typ; String typName = prim.getPrimitiveTypeCode().toString(); List<VariableDeclarationFragment> vars = node.fragments(); for (VariableDeclarationFragment var : vars) { map.put(var.getName().getIdentifier(), typName); } } if (typ.isParameterizedType()) { ParameterizedType prim = (ParameterizedType) typ; String typName = prim.getType().toString(); List<VariableDeclarationFragment> vars = node.fragments(); for (VariableDeclarationFragment var : vars) { map.put(var.getName().getIdentifier(), typName); } } if (typ.isArrayType()) { ArrayType prim = (ArrayType) typ; String typName = "Array"; List<VariableDeclarationFragment> vars = node.fragments(); for (VariableDeclarationFragment var : vars) { map.put(var.getName().getIdentifier(), typName); } } return true; }
public static Class<?> getActualType(Type genericType, final int pos) { if (genericType == null) return null; if (!ParameterizedType.class.isAssignableFrom(genericType.getClass())) { if (genericType instanceof TypeVariable) genericType = getType(((TypeVariable<?>) genericType).getBounds(), pos); else if (genericType instanceof WildcardType) { final WildcardType wildcardType = (WildcardType) genericType; Type[] bounds = wildcardType.getLowerBounds(); if (bounds.length == 0) bounds = wildcardType.getUpperBounds(); genericType = getType(bounds, pos); } final Class<?> cls = (Class<?>) genericType; return cls.isArray() ? cls.getComponentType() : cls; } final ParameterizedType paramType = (ParameterizedType) genericType; final Type t = getType(paramType.getActualTypeArguments(), pos); return t instanceof Class ? (Class<?>) t : getActualType(t, pos); }
public Type convertToInferred(List typeVars, List inferredTypes) { List newBounds = new ArrayList(); for (Iterator it = typeArguments().iterator(); it.hasNext(); ) { Type next = (Type) it.next(); if (next instanceof IntersectionType) { newBounds.add(inferredTypes.get(typeVars.indexOf(next))); } else if (next instanceof ParameterizedType) { newBounds.add(((ParameterizedType) next).convertToInferred(typeVars, inferredTypes)); } /*else if (next instanceof AnySubType){ newBounds.add(((AnySubType)next).convertToInferred(typeVars, inferredTypes)); }*/ else { newBounds.add(next); } } ParameterizedType converted = ((JL5TypeSystem) typeSystem()).parameterizedType(this.baseType()); converted.typeArguments(newBounds); return converted; }
protected static GenericsInfo ParseGenerics(ParameterizedType parameterized) { GenericsInfo generics = null; if (parameterized != null && parameterized.typeArguments() != null && parameterized.typeArguments().length > 0) { generics = new GenericsInfo(); Type[] types = parameterized.typeArguments(); TypeInfo[] typeInfoList = new TypeInfo[types.length]; for (int i = 0; i < types.length; i++) { typeInfoList[i] = ParseType(types[i]); } generics.typeArguments = typeInfoList; } return generics; }
private static void findAllInterfaceTypes( Map results, ParameterizedType p, Configuration configuration) { Type superType = p.superclassType(); if (superType == null) return; addAllInterfaceTypes( results, superType, superType instanceof ClassDoc ? ((ClassDoc) superType).interfaceTypes() : ((ParameterizedType) superType).interfaceTypes(), false, configuration); }
// e.g. C[T1,T2]:Super[Int, T1] -> C[Int,Double]:Super[Int,Int] private final boolean instantiateCheck( Type<?>[] params, RuntimeType<?> rtt, Object o_or_any_or_subParams) { if (rtt.parents != null) { for (Type<?> t : rtt.parents) { if (javaClass.isAssignableFrom(t.getJavaClass())) { if (t instanceof ParameterizedType<?>) { ParameterizedType<?> pt = (ParameterizedType<?>) t; Type<?>[] origTypeArgumentsT = pt.getActualTypeArguments(); Type<?>[] resolvedTypeArgumentsT = new Type<?>[origTypeArgumentsT.length]; for (int i = 0; i < origTypeArgumentsT.length; i++) { resolvedTypeArgumentsT[i] = resolveUnresolvedType(rtt, o_or_any_or_subParams, origTypeArgumentsT[i]); } if (isAssignableFrom(params, pt.getRawType(), resolvedTypeArgumentsT)) { return true; } } } } } return false; }