java.lang.reflect.GenericArrayType Java Examples

The following examples show how to use java.lang.reflect.GenericArrayType. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: MXBeanIntrospector.java    From jdk8u-dev-jdk with GNU General Public License v2.0 6 votes vote down vote up
static String typeName(Type type) {
    if (type instanceof Class<?>) {
        Class<?> c = (Class<?>) type;
        if (c.isArray())
            return typeName(c.getComponentType()) + "[]";
        else
            return c.getName();
    } else if (type instanceof GenericArrayType) {
        GenericArrayType gat = (GenericArrayType) type;
        return typeName(gat.getGenericComponentType()) + "[]";
    } else if (type instanceof ParameterizedType) {
        ParameterizedType pt = (ParameterizedType) type;
        StringBuilder sb = new StringBuilder();
        sb.append(typeName(pt.getRawType())).append("<");
        String sep = "";
        for (Type t : pt.getActualTypeArguments()) {
            sb.append(sep).append(typeName(t));
            sep = ", ";
        }
        return sb.append(">").toString();
    } else
        return "???";
}
 
Example #2
Source File: DefaultMXBeanMappingFactory.java    From JDKSourceCode1.8 with MIT License 6 votes vote down vote up
@Override
final Object fromNonNullOpenValue(Object openValue)
        throws InvalidObjectException {
    final Object[] openArray = (Object[]) openValue;
    final Type javaType = getJavaType();
    final Object[] valueArray;
    final Type componentType;
    if (javaType instanceof GenericArrayType) {
        componentType =
            ((GenericArrayType) javaType).getGenericComponentType();
    } else if (javaType instanceof Class<?> &&
               ((Class<?>) javaType).isArray()) {
        componentType = ((Class<?>) javaType).getComponentType();
    } else {
        throw new IllegalArgumentException("Not an array: " +
                                           javaType);
    }
    valueArray = (Object[]) Array.newInstance((Class<?>) componentType,
                                              openArray.length);
    for (int i = 0; i < openArray.length; i++)
        valueArray[i] = elementMapping.fromOpenValue(openArray[i]);
    return valueArray;
}
 
Example #3
Source File: JSONParser.java    From elasticsearch-jdbc with MIT License 6 votes vote down vote up
public Deserializer getDeserializer(Type type) {

        Deserializer deserializer = deserializerMap.get(type);
        if (deserializer != null) {
            return deserializer;
        }

        if (type instanceof Class<?>) {
            return getDeserializer((Class<?>) type, type);
        }

        if (type instanceof ParameterizedType) {
            Type rawType = ((ParameterizedType) type).getRawType();
            if (rawType instanceof Class<?>) {
                return getDeserializer((Class<?>) rawType, type);
            } else {
                return getDeserializer(rawType);
            }
        }

        if (type instanceof GenericArrayType) {
            return ArrayDeserializer.INSTANCE;
        }

        throw new IllegalArgumentException("can't get the Deserializer by " + type);
    }
 
Example #4
Source File: JAXBSchemaInitializer.java    From cxf with Apache License 2.0 6 votes vote down vote up
static Class<?> getArrayComponentType(Type cls) {
    if (cls instanceof Class) {
        if (((Class<?>)cls).isArray()) {
            return ((Class<?>)cls).getComponentType();
        }
        return (Class<?>)cls;
    } else if (cls instanceof ParameterizedType) {
        for (Type t2 : ((ParameterizedType)cls).getActualTypeArguments()) {
            return getArrayComponentType(t2);
        }
    } else if (cls instanceof GenericArrayType) {
        GenericArrayType gt = (GenericArrayType)cls;
        Class<?> ct = (Class<?>) gt.getGenericComponentType();
        return Array.newInstance(ct, 0).getClass();
    }
    return null;
}
 
Example #5
Source File: InjectorImpl.java    From crate with Apache License 2.0 6 votes vote down vote up
/**
 * Converts a binding for a {@code Key<TypeLiteral<T>>} to the value {@code TypeLiteral<T>}. It's
 * a bit awkward because we have to pull out the inner type in the type literal.
 */
private <T> BindingImpl<TypeLiteral<T>> createTypeLiteralBinding(
        Key<TypeLiteral<T>> key, Errors errors) throws ErrorsException {
    Type typeLiteralType = key.getTypeLiteral().getType();
    if (!(typeLiteralType instanceof ParameterizedType)) {
        throw errors.cannotInjectRawTypeLiteral().toException();
    }

    ParameterizedType parameterizedType = (ParameterizedType) typeLiteralType;
    Type innerType = parameterizedType.getActualTypeArguments()[0];

    // this is unfortunate. We don't support building TypeLiterals for type variable like 'T'. If
    // this proves problematic, we can probably fix TypeLiteral to support type variables
    if (!(innerType instanceof Class)
            && !(innerType instanceof GenericArrayType)
            && !(innerType instanceof ParameterizedType)) {
        throw errors.cannotInjectTypeLiteralOf(innerType).toException();
    }

    @SuppressWarnings("unchecked") // by definition, innerType == T, so this is safe
            TypeLiteral<T> value = (TypeLiteral<T>) TypeLiteral.get(innerType);
    InternalFactory<TypeLiteral<T>> factory = new ConstantFactory<>(
            Initializables.of(value));
    return new InstanceBindingImpl<>(this, key, SourceProvider.UNKNOWN_SOURCE,
            factory, emptySet(), value);
}
 
Example #6
Source File: Reflector.java    From Genius-Android with Apache License 2.0 6 votes vote down vote up
/**
 * Get the underlying class for a type, or null if the type is a variable
 * type.
 *
 * @param type the type
 * @return the underlying class
 */
public static Class<?> getClass(Type type) {
    if (type instanceof Class) {
        return (Class) type;
    } else if (type instanceof ParameterizedType) {
        return getClass(((ParameterizedType) type).getRawType());
    } else if (type instanceof GenericArrayType) {
        Type componentType = ((GenericArrayType) type).getGenericComponentType();
        Class<?> componentClass = getClass(componentType);
        if (componentClass != null) {
            return Array.newInstance(componentClass, 0).getClass();
        } else {
            return null;
        }
    } else {
        return null;
    }
}
 
Example #7
Source File: ClassUtils.java    From jprotobuf with Apache License 2.0 6 votes vote down vote up
public static Class<?> getGenericClass(Class<?> cls, int i) {
    try {
        ParameterizedType parameterizedType = ((ParameterizedType) cls.getGenericInterfaces()[0]);
        Object genericClass = parameterizedType.getActualTypeArguments()[i];
        if (genericClass instanceof ParameterizedType) { // 处理多级泛型
            return (Class<?>) ((ParameterizedType) genericClass).getRawType();
        } else if (genericClass instanceof GenericArrayType) { // 处理数组泛型
            return (Class<?>) ((GenericArrayType) genericClass).getGenericComponentType();
        } else if (genericClass != null) {
            return (Class<?>) genericClass;
        }
    } catch (Throwable e) {
        toString(e);
    }
    if (cls.getSuperclass() != null) {
        return getGenericClass(cls.getSuperclass(), i);
    } else {
        throw new IllegalArgumentException(cls.getName() + " generic type undefined!");
    }
}
 
Example #8
Source File: TypeUtils.java    From dolphin-platform with Apache License 2.0 6 votes vote down vote up
/**
 * <p>Checks if the subject type may be implicitly cast to the target type
 * following the Java generics rules.</p>
 *
 * @param type           the subject type to be assigned to the target type
 * @param toType         the target type
 * @param typeVarAssigns optional map of type variable assignments
 * @return {@code true} if {@code type} is assignable to {@code toType}.
 */
private static boolean isAssignable(final Type type, final Type toType,
                                    final Map<TypeVariable<?>, Type> typeVarAssigns) {
    if (toType == null || toType instanceof Class<?>) {
        return isAssignable(type, (Class<?>) toType);
    }

    if (toType instanceof ParameterizedType) {
        return isAssignable(type, (ParameterizedType) toType, typeVarAssigns);
    }

    if (toType instanceof GenericArrayType) {
        return isAssignable(type, (GenericArrayType) toType, typeVarAssigns);
    }

    if (toType instanceof WildcardType) {
        return isAssignable(type, (WildcardType) toType, typeVarAssigns);
    }

    if (toType instanceof TypeVariable<?>) {
        return isAssignable(type, (TypeVariable<?>) toType, typeVarAssigns);
    }

    throw new IllegalStateException("found an unhandled type: " + toType);
}
 
Example #9
Source File: TypeUtils.java    From ldp4j with Apache License 2.0 6 votes vote down vote up
private String toString(Type type, boolean qualify) {
	visited.add(type);
	String result=null;
	if (type instanceof TypeVariable) {
		result=printTypeVariable((TypeVariable<?>) type,qualify);
	} else if (type instanceof ParameterizedType) {
		result=printParameterizedType((ParameterizedType) type,qualify);
	} else if (type instanceof Class) {
		result=printClass((Class<?>) type,qualify);
	} else if (type instanceof GenericArrayType) {
		result=printGenericArrayDeclaration((GenericArrayType) type,qualify);
	} else if (type instanceof WildcardType) {
		result=printWildcardType((WildcardType) type);
	} else {
		throw new IllegalStateException("Unknown type '"+type+"'");
	}
	return result;
}
 
Example #10
Source File: Jaxb2Marshaller.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Override
public boolean supports(Type genericType) {
	if (genericType instanceof ParameterizedType) {
		ParameterizedType parameterizedType = (ParameterizedType) genericType;
		if (JAXBElement.class == parameterizedType.getRawType() &&
				parameterizedType.getActualTypeArguments().length == 1) {
			Type typeArgument = parameterizedType.getActualTypeArguments()[0];
			if (typeArgument instanceof Class) {
				Class<?> classArgument = (Class<?>) typeArgument;
				return ((classArgument.isArray() && Byte.TYPE == classArgument.getComponentType()) ||
						isPrimitiveWrapper(classArgument) || isStandardClass(classArgument) ||
						supportsInternal(classArgument, false));
			}
			else if (typeArgument instanceof GenericArrayType) {
				GenericArrayType arrayType = (GenericArrayType) typeArgument;
				return (Byte.TYPE == arrayType.getGenericComponentType());
			}
		}
	}
	else if (genericType instanceof Class) {
		Class<?> clazz = (Class<?>) genericType;
		return supportsInternal(clazz, this.checkForXmlRootElement);
	}
	return false;
}
 
Example #11
Source File: ReflectUtils.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
public static <T> Class<T> getFieldArgument(Class<?> genericCls, String fieldName) {
  try {
    Type generic = FieldUtils.getField(genericCls, fieldName).getGenericType();
    TypeToken<?> token = TypeToken.of(genericCls).resolveType(generic);
    Type fieldType = token.getType();
    Type argument = ((ParameterizedType) fieldType).getActualTypeArguments()[0];
    if (argument instanceof GenericArrayType) {
      return (Class<T>) TypeToken.of(argument).getRawType();
    }

    return (Class<T>) argument;
  } catch (Throwable e) {
    throw new IllegalStateException("Failed to get generic argument.", e);
  }
}
 
Example #12
Source File: MXBeanIntrospector.java    From openjdk-8 with GNU General Public License v2.0 6 votes vote down vote up
static String typeName(Type type) {
    if (type instanceof Class<?>) {
        Class<?> c = (Class<?>) type;
        if (c.isArray())
            return typeName(c.getComponentType()) + "[]";
        else
            return c.getName();
    } else if (type instanceof GenericArrayType) {
        GenericArrayType gat = (GenericArrayType) type;
        return typeName(gat.getGenericComponentType()) + "[]";
    } else if (type instanceof ParameterizedType) {
        ParameterizedType pt = (ParameterizedType) type;
        StringBuilder sb = new StringBuilder();
        sb.append(typeName(pt.getRawType())).append("<");
        String sep = "";
        for (Type t : pt.getActualTypeArguments()) {
            sb.append(sep).append(typeName(t));
            sep = ", ";
        }
        return sb.append(">").toString();
    } else
        return "???";
}
 
Example #13
Source File: MXBeanIntrospector.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
static String typeName(Type type) {
    if (type instanceof Class<?>) {
        Class<?> c = (Class<?>) type;
        if (c.isArray())
            return typeName(c.getComponentType()) + "[]";
        else
            return c.getName();
    } else if (type instanceof GenericArrayType) {
        GenericArrayType gat = (GenericArrayType) type;
        return typeName(gat.getGenericComponentType()) + "[]";
    } else if (type instanceof ParameterizedType) {
        ParameterizedType pt = (ParameterizedType) type;
        StringBuilder sb = new StringBuilder();
        sb.append(typeName(pt.getRawType())).append("<");
        String sep = "";
        for (Type t : pt.getActualTypeArguments()) {
            sb.append(sep).append(typeName(t));
            sep = ", ";
        }
        return sb.append(">").toString();
    } else
        return "???";
}
 
Example #14
Source File: DefaultMXBeanMappingFactory.java    From openjdk-8-source with GNU General Public License v2.0 6 votes vote down vote up
@Override
final Object fromNonNullOpenValue(Object openValue)
        throws InvalidObjectException {
    final Object[] openArray = (Object[]) openValue;
    final Type javaType = getJavaType();
    final Object[] valueArray;
    final Type componentType;
    if (javaType instanceof GenericArrayType) {
        componentType =
            ((GenericArrayType) javaType).getGenericComponentType();
    } else if (javaType instanceof Class<?> &&
               ((Class<?>) javaType).isArray()) {
        componentType = ((Class<?>) javaType).getComponentType();
    } else {
        throw new IllegalArgumentException("Not an array: " +
                                           javaType);
    }
    valueArray = (Object[]) Array.newInstance((Class<?>) componentType,
                                              openArray.length);
    for (int i = 0; i < openArray.length; i++)
        valueArray[i] = elementMapping.fromOpenValue(openArray[i]);
    return valueArray;
}
 
Example #15
Source File: DefaultMXBeanMappingFactory.java    From jdk1.8-source-analysis with Apache License 2.0 6 votes vote down vote up
@Override
final Object fromNonNullOpenValue(Object openValue)
        throws InvalidObjectException {
    final Object[] openArray = (Object[]) openValue;
    final Type javaType = getJavaType();
    final Object[] valueArray;
    final Type componentType;
    if (javaType instanceof GenericArrayType) {
        componentType =
            ((GenericArrayType) javaType).getGenericComponentType();
    } else if (javaType instanceof Class<?> &&
               ((Class<?>) javaType).isArray()) {
        componentType = ((Class<?>) javaType).getComponentType();
    } else {
        throw new IllegalArgumentException("Not an array: " +
                                           javaType);
    }
    valueArray = (Object[]) Array.newInstance((Class<?>) componentType,
                                              openArray.length);
    for (int i = 0; i < openArray.length; i++)
        valueArray[i] = elementMapping.fromOpenValue(openArray[i]);
    return valueArray;
}
 
Example #16
Source File: Generics.java    From dekorate with Apache License 2.0 6 votes vote down vote up
/**
 * Get the underlying class for a type, or null if the type is a variable type.
 * @param type the type
 * @return the underlying class
 */
public static Class<?> getClass(Type type) {
    if (type instanceof Class) {
        return (Class) type;
    }
    else if (type instanceof ParameterizedType) {
        return getClass(((ParameterizedType) type).getRawType());
    }
    else if (type instanceof GenericArrayType) {
        Type componentType = ((GenericArrayType) type).getGenericComponentType();
        Class<?> componentClass = getClass(componentType);
        if (componentClass != null ) {
            return Array.newInstance(componentClass, 0).getClass();
        }
        else {
            return null;
        }
    }
    else {
        return null;
    }
}
 
Example #17
Source File: ReflectionNavigator.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
public boolean isArray(Type t) {
    if (t instanceof Class) {
        Class c = (Class) t;
        return c.isArray();
    }
    if (t instanceof GenericArrayType) {
        return true;
    }
    return false;
}
 
Example #18
Source File: ReflectionNavigator.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
public boolean isArrayButNotByteArray(Type t) {
    if (t instanceof Class) {
        Class c = (Class) t;
        return c.isArray() && c != byte[].class;
    }
    if (t instanceof GenericArrayType) {
        t = ((GenericArrayType) t).getGenericComponentType();
        return t != Byte.TYPE;
    }
    return false;
}
 
Example #19
Source File: TestPlainArrayNotGeneric.java    From native-obfuscator with GNU General Public License v3.0 5 votes vote down vote up
private static void check2(Type t, String what) {
    if (t instanceof ParameterizedType) {
        ParameterizedType pt = (ParameterizedType) t;
        check(pt.getActualTypeArguments(), "type argument", what);
    } else if (t instanceof TypeVariable) {
        TypeVariable<?> tv = (TypeVariable<?>) t;
        check(tv.getBounds(), "bound", what);
        GenericDeclaration gd = tv.getGenericDeclaration();
        if (gd instanceof Type)
            check((Type) gd, "declaration containing " + what);
    } else if (t instanceof WildcardType) {
        WildcardType wt = (WildcardType) t;
        check(wt.getLowerBounds(), "lower bound", "wildcard type in " + what);
        check(wt.getUpperBounds(), "upper bound", "wildcard type in " + what);
    } else if (t instanceof Class<?>) {
        Class<?> c = (Class<?>) t;
        check(c.getGenericInterfaces(), "superinterface", c.toString());
        check(c.getGenericSuperclass(), "superclass of " + c);
        check(c.getTypeParameters(), "type parameter", c.toString());
    } else if (t instanceof GenericArrayType) {
        GenericArrayType gat = (GenericArrayType) t;
        Type comp = gat.getGenericComponentType();
        if (comp instanceof Class) {
            fail("Type " + t + " uses GenericArrayType when plain " +
                    "array would do, in " + what);
        } else
            check(comp, "component type of " + what);
    } else {
        fail("TEST BUG: mutant Type " + t + " (a " + t.getClass().getName() + ")");
    }
}
 
Example #20
Source File: ArrayTypeAdapter.java    From framework with GNU Affero General Public License v3.0 5 votes vote down vote up
@SuppressWarnings({"unchecked", "rawtypes"})
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> typeToken) {
  Type type = typeToken.getType();
  if (!(type instanceof GenericArrayType || type instanceof Class && ((Class<?>) type).isArray())) {
    return null;
  }

  Type componentType = $Gson$Types.getArrayComponentType(type);
  TypeAdapter<?> componentTypeAdapter = gson.getAdapter(TypeToken.get(componentType));
  return new ArrayTypeAdapter(
          gson, componentTypeAdapter, $Gson$Types.getRawType(componentType));
}
 
Example #21
Source File: GenericArrayTypeImpl.java    From java-n-IDE-for-Android with Apache License 2.0 5 votes vote down vote up
@Override
public boolean equals(Object o) {
    if (o instanceof GenericArrayType) {
        GenericArrayType that = (GenericArrayType) o;

        Type thatComponentType = that.getGenericComponentType();
        return genericComponentType == null ?
            thatComponentType == null :
            genericComponentType.equals(thatComponentType);
    } else
        return false;
}
 
Example #22
Source File: ArrayDeserializer.java    From light-task-scheduler with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings({"unchecked", "rawtypes"})
public <T> T deserialize(Object object, Type type) {

    JSONArray jsonArray;
    if (object instanceof JSONArray) {
        jsonArray = (JSONArray) object;
    } else {
        jsonArray = new JSONArray(object);
    }

    Class componentClass = null;
    Type componentType = null;
    if (type instanceof GenericArrayType) {
        componentType = ((GenericArrayType) type).getGenericComponentType();
        if (componentType instanceof TypeVariable) {
            TypeVariable<?> componentVar = (TypeVariable<?>) componentType;
            componentType = componentVar.getBounds()[0];
        }
        if (componentType instanceof Class<?>) {
            componentClass = (Class<?>) componentType;
        }
    } else {
        Class clazz = (Class) type;
        componentType = componentClass = clazz.getComponentType();
    }

    int size = jsonArray.size();
    Object array = Array.newInstance(componentClass, size);

    for (int i = 0; i < size; i++) {
        Object value = jsonArray.get(i);

        Deserializer deserializer = JSONParser.getDeserializer(componentClass);
        Array.set(array, i, deserializer.deserialize(value, componentType));
    }

    return (T) array;
}
 
Example #23
Source File: TypeConverter.java    From jstarcraft-core with Apache License 2.0 5 votes vote down vote up
@Override
public Type readValueFrom(CsvReader context, Type type) throws Exception {
    Iterator<String> in = context.getInputStream();
    String check = in.next();
    if (StringUtility.isEmpty(check)) {
        return null;
    }
    int code = Integer.valueOf(check);
    ClassDefinition definition = context.getClassDefinition(code);
    if (definition.getType() == Class.class) {
        code = Integer.valueOf(in.next());
        definition = context.getClassDefinition(code);
        return definition.getType();
    } else if (definition.getType() == GenericArrayType.class) {
        if (type == Class.class) {
            type = readValueFrom(context, type);
            Class<?> clazz = Class.class.cast(type);
            return Array.newInstance(clazz, 0).getClass();
        } else {
            type = readValueFrom(context, type);
            return TypeUtility.genericArrayType(type);
        }
    } else if (definition.getType() == ParameterizedType.class) {
        code = Integer.valueOf(in.next());
        definition = context.getClassDefinition(code);
        Integer length = Integer.valueOf(in.next());
        Type[] types = new Type[length];
        for (int index = 0; index < length; index++) {
            types[index] = readValueFrom(context, type);
        }
        return TypeUtility.parameterize(definition.getType(), types);
    } else {
        throw new CodecConvertionException();
    }
}
 
Example #24
Source File: ArrayTypeAdapter.java    From gson with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings({"unchecked", "rawtypes"})
@Override public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> typeToken) {
  Type type = typeToken.getType();
  if (!(type instanceof GenericArrayType || type instanceof Class && ((Class<?>) type).isArray())) {
    return null;
  }

  Type componentType = $Gson$Types.getArrayComponentType(type);
  TypeAdapter<?> componentTypeAdapter = gson.getAdapter(TypeToken.get(componentType));
  return new ArrayTypeAdapter(
          gson, componentTypeAdapter, $Gson$Types.getRawType(componentType));
}
 
Example #25
Source File: TypeUtils.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Get the raw type of a Java type, given its context. Primarily for use
 * with {@link TypeVariable}s and {@link GenericArrayType}s, or when you do
 * not know the runtime type of <code>type</code>: if you know you have a
 * {@link Class} instance, it is already raw; if you know you have a
 * {@link ParameterizedType}, its raw type is only a method call away.
 * @param enclosingType context
 * @param type to read
 * @return Class<?>
 */
// original code stolen from commons [proxy]'s 2.0 branch, then kneaded until firm
public static Class<?> getRawType(Type enclosingType, Type type) {
    if (type instanceof Class<?>) {
        // it is raw, no problem
        return (Class<?>) type;
    }
    if (type instanceof ParameterizedType) {
        // simple enough to get the raw type of a ParameterizedType
        return (Class<?>) ((ParameterizedType) type).getRawType();
    }
    if (type instanceof TypeVariable<?>) {
        Validate.notNull(enclosingType,
                "Cannot get raw type of TypeVariable without enclosing type");
        // resolve the variable against the enclosing type, hope for the best (casting)
        return (Class<?>) resolveVariable(enclosingType, (TypeVariable<?>) type);
    }
    if (type instanceof GenericArrayType) {
        Validate.notNull(enclosingType,
                "Cannot get raw type of GenericArrayType without enclosing type");
        // not included in original code, but not too difficult:  just have to get raw component type...
        Class<?> rawComponentType = getRawType(enclosingType, ((GenericArrayType) type)
                .getGenericComponentType());
        // ...and know how to reflectively create array types, uncommon but not unheard of:
        return Array.newInstance(rawComponentType, 0).getClass();
    }
    throw new IllegalArgumentException(String.valueOf(type));
}
 
Example #26
Source File: ReflectionNavigator.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
/**
 * JDK 5.0 has a bug of creating {@link GenericArrayType} where it shouldn't.
 * fix that manually to work around the problem.
 *
 * See bug 6202725.
 */
private Type fix(Type t) {
    if (!(t instanceof GenericArrayType)) {
        return t;
    }

    GenericArrayType gat = (GenericArrayType) t;
    if (gat.getGenericComponentType() instanceof Class) {
        Class c = (Class) gat.getGenericComponentType();
        return Array.newInstance(c, 0).getClass();
    }

    return t;
}
 
Example #27
Source File: Util.java    From httplite with Apache License 2.0 5 votes vote down vote up
public static Class<?> getRawType(Type type) {
    if (type instanceof Class<?>) {
        // Type is a normal class.
        return (Class<?>) type;

    } else if (type instanceof ParameterizedType) {
        ParameterizedType parameterizedType = (ParameterizedType) type;

        // I'm not exactly sure why getRawType() returns Type instead of Class. Neal isn't either but
        // suspects some pathological case related to nested classes exists.
        Type rawType = parameterizedType.getRawType();
        if (!(rawType instanceof Class)) throw new IllegalArgumentException();
        return (Class<?>) rawType;

    } else if (type instanceof GenericArrayType) {
        Type componentType = ((GenericArrayType) type).getGenericComponentType();
        return Array.newInstance(getRawType(componentType), 0).getClass();

    } else if (type instanceof TypeVariable) {
        // We could use the variable's bounds, but that won't work if there are multiple. Having a raw
        // type that's more general than necessary is okay.
        return Object.class;

    } else if (type instanceof WildcardType) {
        return getRawType(((WildcardType) type).getUpperBounds()[0]);

    } else {
        String className = type == null ? "null" : type.getClass().getName();
        throw new IllegalArgumentException("Expected a Class, ParameterizedType, or "
                + "GenericArrayType, but <" + type + "> is of type " + className);
    }
}
 
Example #28
Source File: Class.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
private static Class<?> toClass(Type o) {
   if (o instanceof GenericArrayType)
       return Array.newInstance(toClass(((GenericArrayType)o).getGenericComponentType()),
                                0)
           .getClass();
   return (Class<?>)o;
}
 
Example #29
Source File: TestPlainArrayNotGeneric.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
private static void check2(Type t, String what) {
    if (t instanceof ParameterizedType) {
        ParameterizedType pt = (ParameterizedType) t;
        check(pt.getActualTypeArguments(), "type argument", what);
    } else if (t instanceof TypeVariable) {
        TypeVariable<?> tv = (TypeVariable<?>) t;
        check(tv.getBounds(), "bound", what);
        GenericDeclaration gd = tv.getGenericDeclaration();
        if (gd instanceof Type)
            check((Type) gd, "declaration containing " + what);
    } else if (t instanceof WildcardType) {
        WildcardType wt = (WildcardType) t;
        check(wt.getLowerBounds(), "lower bound", "wildcard type in " + what);
        check(wt.getUpperBounds(), "upper bound", "wildcard type in " + what);
    } else if (t instanceof Class<?>) {
        Class<?> c = (Class<?>) t;
        check(c.getGenericInterfaces(), "superinterface", c.toString());
        check(c.getGenericSuperclass(), "superclass of " + c);
        check(c.getTypeParameters(), "type parameter", c.toString());
    } else if (t instanceof GenericArrayType) {
        GenericArrayType gat = (GenericArrayType) t;
        Type comp = gat.getGenericComponentType();
        if (comp instanceof Class) {
            fail("Type " + t + " uses GenericArrayType when plain " +
                    "array would do, in " + what);
        } else
            check(comp, "component type of " + what);
    } else {
        fail("TEST BUG: mutant Type " + t + " (a " + t.getClass().getName() + ")");
    }
}
 
Example #30
Source File: Reflections.java    From quarkus with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public static <T> Class<T> getRawType(Type type) {
    if (type instanceof Class<?>) {
        return (Class<T>) type;
    }
    if (type instanceof ParameterizedType) {
        if (((ParameterizedType) type).getRawType() instanceof Class<?>) {
            return (Class<T>) ((ParameterizedType) type).getRawType();
        }
    }
    if (type instanceof TypeVariable<?>) {
        TypeVariable<?> variable = (TypeVariable<?>) type;
        Type[] bounds = variable.getBounds();
        return getBound(bounds);
    }
    if (type instanceof WildcardType) {
        WildcardType wildcard = (WildcardType) type;
        return getBound(wildcard.getUpperBounds());
    }
    if (type instanceof GenericArrayType) {
        GenericArrayType genericArrayType = (GenericArrayType) type;
        Class<?> rawType = getRawType(genericArrayType.getGenericComponentType());
        if (rawType != null) {
            return (Class<T>) Array.newInstance(rawType, 0).getClass();
        }
    }
    return null;
}