List of usage examples for java.lang.reflect GenericArrayType getGenericComponentType
Type getGenericComponentType();
From source file:eu.stratosphere.api.java.typeutils.TypeExtractor.java
@SuppressWarnings({ "unchecked", "rawtypes" }) private static <IN1, IN2, OUT> TypeInformation<OUT> createTypeInfoWithTypeHierarchy( ArrayList<Type> typeHierarchy, Type t, TypeInformation<IN1> in1Type, TypeInformation<IN2> in2Type) { // check if type is a subclass of tuple if ((t instanceof Class<?> && Tuple.class.isAssignableFrom((Class<?>) t)) || (t instanceof ParameterizedType && Tuple.class.isAssignableFrom((Class<?>) ((ParameterizedType) t).getRawType()))) { Type curT = t;/* ww w . j a va 2 s .c o m*/ // do not allow usage of Tuple as type if (curT instanceof Class<?> && ((Class<?>) curT).equals(Tuple.class)) { throw new InvalidTypesException( "Usage of class Tuple as a type is not allowed. Use a concrete subclass (e.g. Tuple1, Tuple2, etc.) instead."); } // go up the hierarchy until we reach immediate child of Tuple (with or without generics) // collect the types while moving up for a later top-down while (!(curT instanceof ParameterizedType && ((Class<?>) ((ParameterizedType) curT).getRawType()).getSuperclass().equals(Tuple.class)) && !(curT instanceof Class<?> && ((Class<?>) curT).getSuperclass().equals(Tuple.class))) { typeHierarchy.add(curT); // parameterized type if (curT instanceof ParameterizedType) { curT = ((Class<?>) ((ParameterizedType) curT).getRawType()).getGenericSuperclass(); } // class else { curT = ((Class<?>) curT).getGenericSuperclass(); } } // check if immediate child of Tuple has generics if (curT instanceof Class<?>) { throw new InvalidTypesException("Tuple needs to be parameterized by using generics."); } ParameterizedType tupleChild = (ParameterizedType) curT; Type[] subtypes = new Type[tupleChild.getActualTypeArguments().length]; // materialize possible type variables for (int i = 0; i < subtypes.length; i++) { // materialize immediate TypeVariables if (tupleChild.getActualTypeArguments()[i] instanceof TypeVariable<?>) { Type varContent = materializeTypeVariable(typeHierarchy, (TypeVariable<?>) tupleChild.getActualTypeArguments()[i]); // variable could not be materialized if (varContent == null) { // add the TypeVariable as subtype for step in next section subtypes[i] = tupleChild.getActualTypeArguments()[i]; } else { // add class or parameterized type subtypes[i] = varContent; } } // class or parameterized type else { subtypes[i] = tupleChild.getActualTypeArguments()[i]; } } TypeInformation<?>[] tupleSubTypes = new TypeInformation<?>[subtypes.length]; for (int i = 0; i < subtypes.length; i++) { // sub type could not be determined with materializing // try to derive the type info of the TypeVariable from the immediate base child input as a last attempt if (subtypes[i] instanceof TypeVariable<?>) { ParameterizedType immediateBaseChild = (ParameterizedType) typeHierarchy .get(typeHierarchy.size() - 1); tupleSubTypes[i] = createTypeInfoWithImmediateBaseChildInput(immediateBaseChild, (TypeVariable<?>) subtypes[i], in1Type, in2Type); // variable could not be determined if (tupleSubTypes[i] == null) { throw new InvalidTypesException("Type of TypeVariable '" + ((TypeVariable<?>) subtypes[i]).getName() + "' in '" + ((TypeVariable<?>) subtypes[i]).getGenericDeclaration() + "' could not be determined. This is most likely a type erasure problem. " + "The type extraction currently supports types with generic variables only in cases where " + "all variables in the return type can be deduced from the input type(s)."); } } else { tupleSubTypes[i] = createTypeInfoWithTypeHierarchy(new ArrayList<Type>(typeHierarchy), subtypes[i], in1Type, in2Type); } } // TODO: Check that type that extends Tuple does not have additional fields. // Right now, these fields are not be serialized by the TupleSerializer. // We might want to add an ExtendedTupleSerializer for that. if (t instanceof Class<?>) { return new TupleTypeInfo(((Class<? extends Tuple>) t), tupleSubTypes); } else if (t instanceof ParameterizedType) { return new TupleTypeInfo(((Class<? extends Tuple>) ((ParameterizedType) t).getRawType()), tupleSubTypes); } } // type depends on another type // e.g. class MyMapper<E> extends MapFunction<String, E> else if (t instanceof TypeVariable) { Type typeVar = materializeTypeVariable(typeHierarchy, (TypeVariable<?>) t); if (typeVar != null) { return createTypeInfoWithTypeHierarchy(typeHierarchy, typeVar, in1Type, in2Type); } // try to derive the type info of the TypeVariable from the immediate base child input as a last attempt else { ParameterizedType immediateBaseChild = (ParameterizedType) typeHierarchy .get(typeHierarchy.size() - 1); TypeInformation<OUT> typeInfo = (TypeInformation<OUT>) createTypeInfoWithImmediateBaseChildInput( immediateBaseChild, (TypeVariable<?>) t, in1Type, in2Type); if (typeInfo != null) { return typeInfo; } else { throw new InvalidTypesException("Type of TypeVariable '" + ((TypeVariable<?>) t).getName() + "' in '" + ((TypeVariable<?>) t).getGenericDeclaration() + "' could not be determined. This is most likely a type erasure problem. " + "The type extraction currently supports types with generic variables only in cases where " + "all variables in the return type can be deduced from the input type(s)."); } } } // arrays with generics // (due to a Java 6 bug, it is possible that BasicArrayTypes also get classified as ObjectArrayTypes // since the JVM classifies e.g. String[] as GenericArrayType instead of Class) else if (t instanceof GenericArrayType) { GenericArrayType genericArray = (GenericArrayType) t; TypeInformation<?> componentInfo = createTypeInfoWithTypeHierarchy(typeHierarchy, genericArray.getGenericComponentType(), in1Type, in2Type); return ObjectArrayTypeInfo.getInfoFor(t, componentInfo); } // objects with generics are treated as raw type else if (t instanceof ParameterizedType) { return getForClass((Class<OUT>) ((ParameterizedType) t).getRawType()); } // no tuple, no TypeVariable, no generic type else if (t instanceof Class) { return getForClass((Class<OUT>) t); } throw new InvalidTypesException("Type Information could not be created."); }
From source file:com.expedia.tesla.compiler.plugins.JavaTypeMapper.java
private Type fromJava(Schema.SchemaBuilder schemaBuilder, java.lang.reflect.Type jt) throws TeslaSchemaException { if (jt instanceof java.lang.Class) { return fromJavaForward(schemaBuilder, (java.lang.Class<?>) jt); } else if (jt instanceof java.lang.reflect.WildcardType) { // ? extends Interface java.lang.reflect.WildcardType wt = (java.lang.reflect.WildcardType) jt; return fromJava(schemaBuilder, wt.getUpperBounds()[0]); } else if (jt instanceof java.lang.reflect.GenericArrayType) { // T[]/*from ww w. j a v a2s . c om*/ java.lang.reflect.GenericArrayType ga = (java.lang.reflect.GenericArrayType) jt; Type elementType = fromJava(schemaBuilder, ga.getGenericComponentType()); return schemaBuilder.addType(String.format("array<%s>", elementType.getTypeId())); } else if (jt instanceof TypeVariable) { // T TypeVariable<?> tv = (TypeVariable<?>) jt; return fromJava(schemaBuilder, tv.getBounds()[0]); } else if (jt instanceof ParameterizedType) { ParameterizedType pt = (ParameterizedType) jt; java.lang.Class<?> rt = (java.lang.Class<?>) pt.getRawType(); if (java.util.Map.class.isAssignableFrom(rt)) { // Map java.lang.reflect.Type kt = (java.lang.reflect.Type) pt.getActualTypeArguments()[0]; java.lang.reflect.Type vt = (java.lang.reflect.Type) pt.getActualTypeArguments()[1]; Type keyType = fromJava(schemaBuilder, kt); Type valueType = fromJava(schemaBuilder, vt); String fs = null; java.lang.Class<?> rawType = (java.lang.Class<?>) pt.getRawType(); if (rawType.isInterface()) { fs = "map<%s,%s>"; } else { fs = "map[" + rawType.getCanonicalName() + "]<%s,%s>"; } String tid = String.format(fs, keyType.getTypeId(), valueType.getTypeId()); return schemaBuilder.addType(tid); } else if (java.util.Collection.class.isAssignableFrom(rt)) { // Collection array (List<?>, Set<?>), use Collection and // ArrayList by default java.lang.reflect.Type et = (java.lang.reflect.Type) pt.getActualTypeArguments()[0]; Type elementType = fromJava(schemaBuilder, et); String fs = null; java.lang.Class<?> rawType = (java.lang.Class<?>) pt.getRawType(); if (rawType.isInterface()) { fs = "array[java.util.Collection,java.util.ArrayList]<%s>"; if (java.util.List.class.isAssignableFrom(rt)) { fs = "array[java.util.List,java.util.ArrayList]<%s>"; } else if (java.util.Set.class.isAssignableFrom(rt)) { fs = "array[java.util.Set,java.util.HashSet]<%s>"; } } else { fs = "array[" + rawType.getCanonicalName() + "]<%s>"; } String tid = String.format(fs, elementType.getTypeId()); return schemaBuilder.addType(tid); } return fromJavaForward(schemaBuilder, rt); } else { throw new TeslaSchemaException("BUG"); } }
From source file:com.link_intersystems.lang.reflect.Class2.java
/** * * @param typeVariable/*ww w . ja v a 2 s . c o m*/ * @return the class that is bound on this {@link Generic} type for the * given {@link TypeVariable} or null if the type bound is not a * Class<?>. If the bound type resolved for the {@link TypeVariable} * is itself a ( {@link ParameterizedType} ) the raw type will be * returned. */ @SuppressWarnings("unchecked") public <C> Class<C> getBoundClass(TypeVariable<?> typeVariable) { Type boundType = getBoundType(typeVariable); if (boundType == null) { return null; } if (boundType instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType) boundType; boundType = parameterizedType.getRawType(); } if (boundType instanceof GenericArrayType) { GenericArrayType genericArrayType = GenericArrayType.class.cast(boundType); Type genericComponentType = genericArrayType.getGenericComponentType(); Class<?> componentType = Class.class.cast(genericComponentType); Object array = Array.newInstance(componentType, 0); boundType = array.getClass(); } return (Class<C>) boundType; }
From source file:com.clark.func.Functions.java
/** * <p>//from www . ja v a 2s.c om * Checks if the subject type may be implicitly cast to the target generic * array type following the Java generics rules. * </p> * * @param type * the subject type to be assigned to the target type * @param toGenericArrayType * the target generic array type * @return true if <code>type</code> is assignable to * <code>toGenericArrayType</code>. */ private static boolean isAssignable(Type type, GenericArrayType toGenericArrayType, Map<TypeVariable<?>, Type> typeVarAssigns) { if (type == null) { return true; } // only a null type can be assigned to null type which // would have cause the previous to return true if (toGenericArrayType == null) { return false; } // all types are assignable to themselves if (toGenericArrayType.equals(type)) { return true; } Type toComponentType = toGenericArrayType.getGenericComponentType(); if (type instanceof Class<?>) { Class<?> cls = (Class<?>) type; // compare the component types return cls.isArray() && isAssignable(cls.getComponentType(), toComponentType, typeVarAssigns); } if (type instanceof GenericArrayType) { // compare the component types return isAssignable(((GenericArrayType) type).getGenericComponentType(), toComponentType, typeVarAssigns); } if (type instanceof WildcardType) { // so long as one of the upper bounds is assignable, it's good for (Type bound : getImplicitUpperBounds((WildcardType) type)) { if (isAssignable(bound, toGenericArrayType)) { return true; } } return false; } if (type instanceof TypeVariable<?>) { // probably should remove the following logic and just return false. // type variables cannot specify arrays as bounds. for (Type bound : getImplicitBounds((TypeVariable<?>) type)) { if (isAssignable(bound, toGenericArrayType)) { return true; } } return false; } if (type instanceof ParameterizedType) { // the raw type of a parameterized type is never an array or // generic array, otherwise the declaration would look like this: // Collection[]< ? extends String > collection; return false; } throw new IllegalStateException("found an unhandled type: " + type); }
From source file:org.alfresco.module.org_alfresco_module_rm.api.PublicAPITestUtil.java
/** * Find all classes that are within the supplied type. For example a {@code Pair<Set<String>, Integer>} contains * references to four classes./*from w ww .j av a 2 s . co m*/ * * @param type The type to examine. * @param processedTypes The set of types which have already been processed. If {@code type} is within this set then * the method returns an empty set, to prevent analysis of the same type multiple times, and to guard * against circular references. The underlying set is updated with the given type. * @return The set of classes used to form the given type. */ private static Set<Class<?>> getClassesFromType(Type type, Set<Type> processedTypes) { Set<Class<?>> returnClasses = new HashSet<>(); if (processedTypes.add(type)) { if (type instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType) type; returnClasses.add((Class<?>) parameterizedType.getRawType()); for (Type t : parameterizedType.getActualTypeArguments()) { returnClasses.addAll(getClassesFromType(t, processedTypes)); } } else if (type instanceof Class) { Class<?> clazz = (Class<?>) type; if (clazz.isArray()) { returnClasses.add(clazz.getComponentType()); } returnClasses.add(clazz); } else if (type instanceof WildcardType) { // No-op - Caller can choose what type to use. } else if (type instanceof TypeVariable<?>) { TypeVariable<?> typeVariable = (TypeVariable<?>) type; for (Type bound : typeVariable.getBounds()) { returnClasses.addAll(getClassesFromType(bound, processedTypes)); } } else if (type instanceof GenericArrayType) { GenericArrayType genericArrayType = (GenericArrayType) type; returnClasses .addAll(getClassesFromType(genericArrayType.getGenericComponentType(), processedTypes)); } else { throw new IllegalStateException("This test was not written to work with type " + type); } } return returnClasses; }
From source file:org.apache.axis2.jaxws.utility.ClassUtils.java
/** * /*from w w w.j a va 2 s .c om*/ */ public static Set<Class> getClasses(Type type, Set<Class> list) { if (list == null) { list = new HashSet<Class>(); } try { if (type instanceof Class) { list.add((Class) type); } if (type instanceof ParameterizedType) { ParameterizedType pt = (ParameterizedType) type; getClasses(pt.getRawType(), list); Type types[] = pt.getActualTypeArguments(); if (types != null) { for (int i = 0; i < types.length; i++) { getClasses(types[i], list); } } } if (type instanceof GenericArrayType) { GenericArrayType gat = (GenericArrayType) type; getClasses(gat.getGenericComponentType(), list); } } catch (Throwable t) { if (log.isDebugEnabled()) { log.debug("Problem occurred in getClasses. Processing continues " + t); } } return list; }
From source file:org.apache.flink.api.java.typeutils.TypeExtractor.java
@SuppressWarnings({ "unchecked", "rawtypes" }) private <IN1, IN2, OUT> TypeInformation<OUT> createTypeInfoWithTypeHierarchy(ArrayList<Type> typeHierarchy, Type t, TypeInformation<IN1> in1Type, TypeInformation<IN2> in2Type) { // check if type information can be created using a type factory final TypeInformation<OUT> typeFromFactory = createTypeInfoFromFactory(t, typeHierarchy, in1Type, in2Type); if (typeFromFactory != null) { return typeFromFactory; }//from w w w.j ava 2 s .c o m // check if type is a subclass of tuple else if (isClassType(t) && Tuple.class.isAssignableFrom(typeToClass(t))) { Type curT = t; // do not allow usage of Tuple as type if (typeToClass(t).equals(Tuple.class)) { throw new InvalidTypesException( "Usage of class Tuple as a type is not allowed. Use a concrete subclass (e.g. Tuple1, Tuple2, etc.) instead."); } // go up the hierarchy until we reach immediate child of Tuple (with or without generics) // collect the types while moving up for a later top-down while (!(isClassType(curT) && typeToClass(curT).getSuperclass().equals(Tuple.class))) { typeHierarchy.add(curT); curT = typeToClass(curT).getGenericSuperclass(); } if (curT == Tuple0.class) { return new TupleTypeInfo(Tuple0.class); } // check if immediate child of Tuple has generics if (curT instanceof Class<?>) { throw new InvalidTypesException("Tuple needs to be parameterized by using generics."); } typeHierarchy.add(curT); // create the type information for the subtypes final TypeInformation<?>[] subTypesInfo = createSubTypesInfo(t, (ParameterizedType) curT, typeHierarchy, in1Type, in2Type, false); // type needs to be treated a pojo due to additional fields if (subTypesInfo == null) { if (t instanceof ParameterizedType) { return (TypeInformation<OUT>) analyzePojo(typeToClass(t), new ArrayList<Type>(typeHierarchy), (ParameterizedType) t, in1Type, in2Type); } else { return (TypeInformation<OUT>) analyzePojo(typeToClass(t), new ArrayList<Type>(typeHierarchy), null, in1Type, in2Type); } } // return tuple info return new TupleTypeInfo(typeToClass(t), subTypesInfo); } // type depends on another type // e.g. class MyMapper<E> extends MapFunction<String, E> else if (t instanceof TypeVariable) { Type typeVar = materializeTypeVariable(typeHierarchy, (TypeVariable<?>) t); if (!(typeVar instanceof TypeVariable)) { return createTypeInfoWithTypeHierarchy(typeHierarchy, typeVar, in1Type, in2Type); } // try to derive the type info of the TypeVariable from the immediate base child input as a last attempt else { TypeInformation<OUT> typeInfo = (TypeInformation<OUT>) createTypeInfoFromInputs((TypeVariable<?>) t, typeHierarchy, in1Type, in2Type); if (typeInfo != null) { return typeInfo; } else { throw new InvalidTypesException("Type of TypeVariable '" + ((TypeVariable<?>) t).getName() + "' in '" + ((TypeVariable<?>) t).getGenericDeclaration() + "' could not be determined. This is most likely a type erasure problem. " + "The type extraction currently supports types with generic variables only in cases where " + "all variables in the return type can be deduced from the input type(s)."); } } } // arrays with generics else if (t instanceof GenericArrayType) { GenericArrayType genericArray = (GenericArrayType) t; Type componentType = genericArray.getGenericComponentType(); // due to a Java 6 bug, it is possible that the JVM classifies e.g. String[] or int[] as GenericArrayType instead of Class if (componentType instanceof Class) { Class<?> componentClass = (Class<?>) componentType; Class<OUT> classArray = (Class<OUT>) (java.lang.reflect.Array.newInstance(componentClass, 0) .getClass()); return getForClass(classArray); } else { TypeInformation<?> componentInfo = createTypeInfoWithTypeHierarchy(typeHierarchy, genericArray.getGenericComponentType(), in1Type, in2Type); Class<?> componentClass = componentInfo.getTypeClass(); Class<OUT> classArray = (Class<OUT>) (java.lang.reflect.Array.newInstance(componentClass, 0) .getClass()); return ObjectArrayTypeInfo.getInfoFor(classArray, componentInfo); } } // objects with generics are treated as Class first else if (t instanceof ParameterizedType) { return (TypeInformation<OUT>) privateGetForClass(typeToClass(t), typeHierarchy, (ParameterizedType) t, in1Type, in2Type); } // no tuple, no TypeVariable, no generic type else if (t instanceof Class) { return privateGetForClass((Class<OUT>) t, typeHierarchy); } throw new InvalidTypesException("Type Information could not be created."); }
From source file:org.apache.hadoop.hive.serde2.typeinfo.TypeInfoUtils.java
public static Type getArrayElementType(Type t) { if (t instanceof Class && ((Class<?>) t).isArray()) { Class<?> arrayClass = (Class<?>) t; return arrayClass.getComponentType(); } else if (t instanceof GenericArrayType) { GenericArrayType arrayType = (GenericArrayType) t; return arrayType.getGenericComponentType(); }//from w ww . j a v a2 s . c om return null; }
From source file:org.apache.sling.stanbol.rest.ported.JerseyUtils.java
/** * Tests if a generic type (may be <?>, <? extends {required}> * or <? super {required}>) is compatible with the required one. * TODO: Should be moved to an utility class * @param required the required class the generic type MUST BE compatible with * @param genericType the required class * @return if the generic type is compatible with the required class *//*from www . java 2s .c o m*/ public static boolean testType(Class<?> required, Type genericType) { //for the examples let assume that a Set is the raw type and the //requested generic type is a Representation with the following class //hierarchy: // Object // -> Representation // -> RdfRepresentation // -> InMemoryRepresentation // -> InputStream // -> Collection<T> boolean typeOK; if (genericType instanceof Class<?>) { //OK // Set<Representation> // Set<Object> //NOT OK // Set<RdfRepresentation> // Set<InputStream> typeOK = ((Class<?>) genericType).isAssignableFrom(required); } else if (genericType instanceof WildcardType) { //In cases <? super {class}>, <? extends {class}, <?> WildcardType wildcardSetType = (WildcardType) genericType; if (wildcardSetType.getLowerBounds().length > 0) { Type lowerBound = wildcardSetType.getLowerBounds()[0]; //OK // Set<? super RdfRepresentation> // Set<? super Representation> //NOT OK // Set<? super InputStream> // Set<? super Collection<Representation>> typeOK = lowerBound instanceof Class<?> && required.isAssignableFrom((Class<?>) lowerBound); } else if (wildcardSetType.getUpperBounds().length > 0) { Type upperBound = wildcardSetType.getUpperBounds()[0]; //OK // Set<? extends Representation> // Set<? extends Object> //NOT OK // Set<? extends RdfRepresentation> // Set<? extends InputStream> // Set<? extends Collection<Representation> typeOK = upperBound instanceof Class<?> && ((Class<?>) upperBound).isAssignableFrom(required); } else { //no upper nor lower bound // Set<?> typeOK = true; } } else if (required.isArray() && genericType instanceof GenericArrayType) { //In case the required type is an array we need also to support //possible generic Array specifications GenericArrayType arrayType = (GenericArrayType) genericType; typeOK = testType(required.getComponentType(), arrayType.getGenericComponentType()); } else { //GenericArrayType but !required.isArray() -> incompatible //TypeVariable -> no variables define -> incompatible typeOK = false; } return typeOK; }
From source file:org.datalorax.populace.core.util.TypeResolver.java
private Type resolveGenericArray(final GenericArrayType type, final TypeToken<?> assigningType) { final Type resolvedComponentType = resolve(type.getGenericComponentType(), assigningType); if (resolvedComponentType.equals(type.getGenericComponentType())) { return type; }//from w ww .j a v a 2 s . co m return TypeUtils.genericArrayType(resolvedComponentType); }