java.lang.reflect.Type

Here are the examples of the java api class java.lang.reflect.Type taken from open source projects.

1. GuavaCallAdapterFactoryTest#responseType()

View license
@Test
public void responseType() {
    Type bodyClass = new TypeToken<ListenableFuture<String>>() {
    }.getType();
    assertThat(factory.get(bodyClass, NO_ANNOTATIONS, retrofit).responseType()).isEqualTo(String.class);
    Type bodyWildcard = new TypeToken<ListenableFuture<? extends String>>() {
    }.getType();
    assertThat(factory.get(bodyWildcard, NO_ANNOTATIONS, retrofit).responseType()).isEqualTo(String.class);
    Type bodyGeneric = new TypeToken<ListenableFuture<List<String>>>() {
    }.getType();
    assertThat(factory.get(bodyGeneric, NO_ANNOTATIONS, retrofit).responseType()).isEqualTo(new TypeToken<List<String>>() {
    }.getType());
    Type responseClass = new TypeToken<ListenableFuture<Response<String>>>() {
    }.getType();
    assertThat(factory.get(responseClass, NO_ANNOTATIONS, retrofit).responseType()).isEqualTo(String.class);
    Type responseWildcard = new TypeToken<ListenableFuture<Response<? extends String>>>() {
    }.getType();
    assertThat(factory.get(responseWildcard, NO_ANNOTATIONS, retrofit).responseType()).isEqualTo(String.class);
    Type resultClass = new TypeToken<ListenableFuture<Response<String>>>() {
    }.getType();
    assertThat(factory.get(resultClass, NO_ANNOTATIONS, retrofit).responseType()).isEqualTo(String.class);
    Type resultWildcard = new TypeToken<ListenableFuture<Response<? extends String>>>() {
    }.getType();
    assertThat(factory.get(resultWildcard, NO_ANNOTATIONS, retrofit).responseType()).isEqualTo(String.class);
}

2. Java8CallAdapterFactoryTest#responseType()

View license
@Test
public void responseType() {
    Type bodyClass = new TypeToken<CompletableFuture<String>>() {
    }.getType();
    assertThat(factory.get(bodyClass, NO_ANNOTATIONS, retrofit).responseType()).isEqualTo(String.class);
    Type bodyWildcard = new TypeToken<CompletableFuture<? extends String>>() {
    }.getType();
    assertThat(factory.get(bodyWildcard, NO_ANNOTATIONS, retrofit).responseType()).isEqualTo(String.class);
    Type bodyGeneric = new TypeToken<CompletableFuture<List<String>>>() {
    }.getType();
    assertThat(factory.get(bodyGeneric, NO_ANNOTATIONS, retrofit).responseType()).isEqualTo(new TypeToken<List<String>>() {
    }.getType());
    Type responseClass = new TypeToken<CompletableFuture<Response<String>>>() {
    }.getType();
    assertThat(factory.get(responseClass, NO_ANNOTATIONS, retrofit).responseType()).isEqualTo(String.class);
    Type responseWildcard = new TypeToken<CompletableFuture<Response<? extends String>>>() {
    }.getType();
    assertThat(factory.get(responseWildcard, NO_ANNOTATIONS, retrofit).responseType()).isEqualTo(String.class);
    Type resultClass = new TypeToken<CompletableFuture<Response<String>>>() {
    }.getType();
    assertThat(factory.get(resultClass, NO_ANNOTATIONS, retrofit).responseType()).isEqualTo(String.class);
    Type resultWildcard = new TypeToken<CompletableFuture<Response<? extends String>>>() {
    }.getType();
    assertThat(factory.get(resultWildcard, NO_ANNOTATIONS, retrofit).responseType()).isEqualTo(String.class);
}

3. TypeUtilsTests#testWithWildcardTypes()

Project: spring-android
Source File: TypeUtilsTests.java
View license
public void testWithWildcardTypes() throws Exception {
    ParameterizedType openObjectsType = (ParameterizedType) getClass().getField("openObjects").getGenericType();
    ParameterizedType openNumbersType = (ParameterizedType) getClass().getField("openNumbers").getGenericType();
    Type storableObjectListType = getClass().getField("storableObjectList").getGenericType();
    Type objectType = getClass().getField("object").getGenericType();
    Type numberType = getClass().getField("number").getGenericType();
    Type stringType = getClass().getField("string").getGenericType();
    // '?'
    Type openWildcard = openObjectsType.getActualTypeArguments()[0];
    // '? extends number'
    Type openNumbersWildcard = openNumbersType.getActualTypeArguments()[0];
    assertTrue(TypeUtils.isAssignable(openWildcard, objectType));
    assertTrue(TypeUtils.isAssignable(openNumbersWildcard, numberType));
    assertFalse(TypeUtils.isAssignable(openNumbersWildcard, stringType));
    assertFalse(TypeUtils.isAssignable(storableObjectListType, openObjectsType));
}

4. TypeResolver#resolveParameterizedType()

Project: cdk
Source File: TypeResolver.java
View license
private ParameterizedType resolveParameterizedType(ParameterizedType type) {
    Type owner = type.getOwnerType();
    Type resolvedOwner = (owner == null) ? null : resolveType(owner);
    Type resolvedRawType = resolveType(type.getRawType());
    Type[] vars = type.getActualTypeArguments();
    Type[] resolvedArgs = new Type[vars.length];
    for (int i = 0; i < vars.length; i++) {
        resolvedArgs[i] = resolveType(vars[i]);
    }
    return Types.newParameterizedTypeWithOwner(resolvedOwner, (Class<?>) resolvedRawType, resolvedArgs);
}

5. WildcardTypeTest#checkLowerBoundedParameter()

Project: j2objc
Source File: WildcardTypeTest.java
View license
private void checkLowerBoundedParameter(Method method) {
    Type genericParameterType = method.getGenericParameterTypes()[0];
    assertInstanceOf(ParameterizedType.class, genericParameterType);
    ParameterizedType parameterizedType = (ParameterizedType) genericParameterType;
    Type[] actualTypeArguments = parameterizedType.getActualTypeArguments();
    assertLenghtOne(actualTypeArguments);
    assertInstanceOf(WildcardType.class, actualTypeArguments[0]);
    WildcardType wildcardType = (WildcardType) actualTypeArguments[0];
    Type[] lowerBounds = wildcardType.getLowerBounds();
    assertLenghtOne(lowerBounds);
    Type lowerBound = lowerBounds[0];
    assertEquals(getTypeParameter(method), lowerBound);
    Type[] upperBounds = wildcardType.getUpperBounds();
    assertEquals(Object.class, upperBounds[0]);
}

6. CallAdapterTest#rawTypes()

Project: retrofit
Source File: CallAdapterTest.java
View license
@Test
public void rawTypes() throws NoSuchMethodException {
    assertThat(getRawType(String.class)).isSameAs(String.class);
    Type listOfString = new TypeToken<List<String>>() {
    }.getType();
    assertThat(getRawType(listOfString)).isSameAs(List.class);
    Type stringArray = new TypeToken<String[]>() {
    }.getType();
    assertThat(getRawType(stringArray)).isSameAs(String[].class);
    Type wild = ((ParameterizedType) new TypeToken<List<? extends CharSequence>>() {
    }.getType()).getActualTypeArguments()[0];
    assertThat(getRawType(wild)).isSameAs(CharSequence.class);
    Type wildParam = ((ParameterizedType) new TypeToken<List<? extends List<String>>>() {
    }.getType()).getActualTypeArguments()[0];
    assertThat(getRawType(wildParam)).isSameAs(List.class);
    Type typeVar = A.class.getDeclaredMethod("method").getGenericReturnType();
    assertThat(getRawType(typeVar)).isSameAs(Object.class);
}

7. TypeUtilsTest#testGetRawType()

Project: commons-lang
Source File: TypeUtilsTest.java
View license
@Test
public void testGetRawType() throws SecurityException, NoSuchFieldException {
    final Type stringParentFieldType = GenericTypeHolder.class.getDeclaredField("stringParent").getGenericType();
    final Type integerParentFieldType = GenericTypeHolder.class.getDeclaredField("integerParent").getGenericType();
    final Type foosFieldType = GenericTypeHolder.class.getDeclaredField("foos").getGenericType();
    final Type genericParentT = GenericParent.class.getTypeParameters()[0];
    Assert.assertEquals(GenericParent.class, TypeUtils.getRawType(stringParentFieldType, null));
    Assert.assertEquals(GenericParent.class, TypeUtils.getRawType(integerParentFieldType, null));
    Assert.assertEquals(List.class, TypeUtils.getRawType(foosFieldType, null));
    Assert.assertEquals(String.class, TypeUtils.getRawType(genericParentT, StringParameterizedChild.class));
    Assert.assertEquals(String.class, TypeUtils.getRawType(genericParentT, stringParentFieldType));
    Assert.assertEquals(Foo.class, TypeUtils.getRawType(Iterable.class.getTypeParameters()[0], foosFieldType));
    Assert.assertEquals(Foo.class, TypeUtils.getRawType(List.class.getTypeParameters()[0], foosFieldType));
    Assert.assertNull(TypeUtils.getRawType(genericParentT, GenericParent.class));
    Assert.assertEquals(GenericParent[].class, TypeUtils.getRawType(GenericTypeHolder.class.getDeclaredField("barParents").getGenericType(), null));
}

8. HierarchyDiscovery#resolveParameterizedType()

Project: deltaspike
Source File: HierarchyDiscovery.java
View license
private Type resolveParameterizedType(ParameterizedType beanType, ParameterizedType parameterizedType) {
    Type rawType = parameterizedType.getRawType();
    Type[] actualTypes = parameterizedType.getActualTypeArguments();
    Type resolvedRawType = resolveType(beanType, beanType, rawType);
    Type[] resolvedActualTypes = new Type[actualTypes.length];
    for (int i = 0; i < actualTypes.length; i++) {
        resolvedActualTypes[i] = resolveType(beanType, beanType, actualTypes[i]);
    }
    // reconstruct ParameterizedType by types resolved TypeVariable.
    return new ParameterizedTypeImpl(resolvedRawType, resolvedActualTypes, parameterizedType.getOwnerType());
}

9. GraphTaskManager#determineClassTypes()

Project: giraph
Source File: GraphTaskManager.java
View license
/**
   * Set the concrete, user-defined choices about generic methods
   * (validated earlier in GiraphRunner) into the Configuration.
   * @param conf the Configuration object for this job run.
   */
public void determineClassTypes(Configuration conf) {
    ImmutableClassesGiraphConfiguration giraphConf = new ImmutableClassesGiraphConfiguration(conf);
    Class<? extends Vertex<I, V, E, M>> vertexClass = giraphConf.getVertexClass();
    List<Class<?>> classList = ReflectionUtils.<Vertex>getTypeArguments(Vertex.class, vertexClass);
    Type vertexIndexType = classList.get(0);
    Type vertexValueType = classList.get(1);
    Type edgeValueType = classList.get(2);
    Type messageValueType = classList.get(3);
    VERTEX_ID_CLASS.set(conf, (Class<WritableComparable>) vertexIndexType);
    VERTEX_VALUE_CLASS.set(conf, (Class<Writable>) vertexValueType);
    EDGE_VALUE_CLASS.set(conf, (Class<Writable>) edgeValueType);
    MESSAGE_VALUE_CLASS.set(conf, (Class<Writable>) messageValueType);
}

10. WildcardTypeTest#checkUpperBoundedParameter()

Project: j2objc
Source File: WildcardTypeTest.java
View license
private void checkUpperBoundedParameter(Method method) {
    assertLenghtOne(method.getGenericParameterTypes());
    Type genericParameterType = method.getGenericParameterTypes()[0];
    assertInstanceOf(ParameterizedType.class, genericParameterType);
    ParameterizedType parameterizedType = (ParameterizedType) genericParameterType;
    Type[] actualTypeArguments = parameterizedType.getActualTypeArguments();
    assertLenghtOne(actualTypeArguments);
    assertInstanceOf(WildcardType.class, actualTypeArguments[0]);
    WildcardType wildcardType = (WildcardType) actualTypeArguments[0];
    assertLenghtZero(wildcardType.getLowerBounds());
    Type[] upperBounds = wildcardType.getUpperBounds();
    assertLenghtOne(upperBounds);
    Type upperBound = upperBounds[0];
    assertEquals(getTypeParameter(method), upperBound);
}

11. GenericClassTest#testStable()

Project: openwebbeans
Source File: GenericClassTest.java
View license
@Test
public void testStable() throws Exception {
    Type parameterizedPigStableType = this.getClass().getDeclaredField("parameterizedPigStable").getGenericType();
    Type parameterizedHorseStableType = this.getClass().getDeclaredField("parameterizedHorseStable").getGenericType();
    Assert.assertNotNull(parameterizedPigStableType);
    Assert.assertNotNull(parameterizedHorseStableType);
    Type pigStableType = this.getClass().getDeclaredField("pigStable").getType().getGenericSuperclass();
    Type horseStableType = this.getClass().getDeclaredField("horseStable").getType().getGenericSuperclass();
    Assert.assertTrue(GenericsUtil.satisfiesDependency(false, false, horseStableType, parameterizedHorseStableType));
    Assert.assertTrue(GenericsUtil.satisfiesDependency(false, false, parameterizedPigStableType, pigStableType));
}

12. HierarchyDiscovery#resolveParameterizedType()

Project: rewrite
Source File: HierarchyDiscovery.java
View license
private Type resolveParameterizedType(ParameterizedType beanType, ParameterizedType parameterizedType) {
    Type rawType = parameterizedType.getRawType();
    Type[] actualTypes = parameterizedType.getActualTypeArguments();
    Type resolvedRawType = resolveType(beanType, beanType, rawType);
    Type[] resolvedActualTypes = new Type[actualTypes.length];
    for (int i = 0; i < actualTypes.length; i++) {
        resolvedActualTypes[i] = resolveType(beanType, beanType, actualTypes[i]);
    }
    // reconstruct ParameterizedType by types resolved TypeVariable.
    return new ParameterizedTypeImpl(resolvedRawType, resolvedActualTypes, parameterizedType.getOwnerType());
}

13. FindTheParameterizedType#main()

View license
/**
     * @param args
     */
public static void main(String[] args) throws Exception {
    Method m = FindTheParameterizedType.class.getMethod("method", Map.class, List.class);
    out.println(m.toString());
    out.println(m.toGenericString());
    Type[] types = m.getGenericParameterTypes();
    ParameterizedType pt = (ParameterizedType) types[0];
    Type keyType = pt.getActualTypeArguments()[0];
    Type valueType = pt.getActualTypeArguments()[1];
    out.printf("   key type: %s\n", rawType(keyType));
    out.printf(" value type: %s\n", rawType(valueType));
    Type listType = types[1];
    out.printf("  list type: %s\n", rawType(listType));
}

14. FindTheParameterizedType#main()

View license
/**
     * @param args
     */
public static void main(String[] args) throws Exception {
    Method m = FindTheParameterizedType.class.getMethod("method", Map.class, List.class);
    out.println(m.toString());
    out.println(m.toGenericString());
    Type[] types = m.getGenericParameterTypes();
    ParameterizedType pt = (ParameterizedType) types[0];
    Type keyType = pt.getActualTypeArguments()[0];
    Type valueType = pt.getActualTypeArguments()[1];
    out.printf("   key type: %s\n", rawType(keyType));
    out.printf(" value type: %s\n", rawType(valueType));
    Type listType = types[1];
    out.printf("  list type: %s\n", rawType(listType));
}

15. GenericTypeResolver#resolveReturnTypeArgument()

View license
/**
     * Resolve the single type argument of the given generic interface against the given
     * target method which is assumed to return the given interface or an implementation
     * of it.
     *
     * @param method     the target method to check the return type of
     * @param genericIfc the generic interface or superclass to resolve the type argument from
     * @return the resolved parameter type of the method return type, or {@code null}
     * if not resolvable or if the single argument is of type {@link WildcardType}.
     */
public static Class<?> resolveReturnTypeArgument(Method method, Class<?> genericIfc) {
    Assert.notNull(method, "method must not be null");
    Type returnType = method.getReturnType();
    Type genericReturnType = method.getGenericReturnType();
    if (returnType.equals(genericIfc)) {
        if (genericReturnType instanceof ParameterizedType) {
            ParameterizedType targetType = (ParameterizedType) genericReturnType;
            Type[] actualTypeArguments = targetType.getActualTypeArguments();
            Type typeArg = actualTypeArguments[0];
            if (!(typeArg instanceof WildcardType)) {
                return (Class<?>) typeArg;
            }
        } else {
            return null;
        }
    }
    return resolveTypeArgument((Class<?>) returnType, genericIfc);
}

16. AggregateConverter#getExactDirectSuperTypes()

Project: aries
Source File: AggregateConverter.java
View license
public static ReifiedType[] getExactDirectSuperTypes(ReifiedType type) {
    Class<?> clazz = type.getRawClass();
    Type[] superInterfaces = clazz.getGenericInterfaces();
    Type superClass = clazz.getGenericSuperclass();
    // the only supertype of an interface without superinterfaces is Object
    if (superClass == null && superInterfaces.length == 0 && clazz.isInterface()) {
        return new ReifiedType[] { new GenericType(Object.class) };
    }
    ReifiedType[] result;
    int resultIndex;
    if (superClass == null) {
        result = new ReifiedType[superInterfaces.length];
        resultIndex = 0;
    } else {
        result = new ReifiedType[superInterfaces.length + 1];
        resultIndex = 1;
        result[0] = mapTypeParameters(superClass, type);
    }
    for (Type superInterface : superInterfaces) {
        result[resultIndex++] = mapTypeParameters(superInterface, type);
    }
    return result;
}

17. ObjectMapper#registerTypeConverter()

View license
public void registerTypeConverter(final TypeConverter typeConverter) {
    //retrieve the target class name of the converter
    Class<? extends TypeConverter> typeConverterClass = typeConverter.getClass();
    Type[] genericInterfaces = typeConverterClass.getGenericInterfaces();
    Type genericInterface = genericInterfaces[0];
    if (!(genericInterface instanceof ParameterizedType)) {
        LOGGER.log(Level.WARNING, "The type converter {0} should be a parametrized type", typeConverterClass.getName());
        return;
    }
    ParameterizedType parameterizedType = (ParameterizedType) genericInterface;
    Type type = parameterizedType.getActualTypeArguments()[1];
    // register the converter
    try {
        Class clazz = Class.forName(getClassName(type));
        typeConverters.put(clazz, typeConverter);
    } catch (ClassNotFoundException e) {
        throw new TypeConverterRegistrationException("Unable to register custom type converter " + typeConverterClass.getName(), e);
    }
}

18. TypesTest#testNewArrayType()

Project: guava
Source File: TypesTest.java
View license
public void testNewArrayType() {
    Type jvmType1 = new TypeCapture<List<String>[]>() {
    }.capture();
    GenericArrayType ourType1 = (GenericArrayType) Types.newArrayType(Types.newParameterizedType(List.class, String.class));
    Type jvmType2 = new TypeCapture<List[]>() {
    }.capture();
    Type ourType2 = Types.newArrayType(List.class);
    new EqualsTester().addEqualityGroup(jvmType1, ourType1).addEqualityGroup(jvmType2, ourType2).testEquals();
    assertEquals(new TypeCapture<List<String>>() {
    }.capture(), ourType1.getGenericComponentType());
    assertEquals(jvmType1.toString(), ourType1.toString());
    assertEquals(jvmType2.toString(), ourType2.toString());
}

19. TypeTokenResolutionTest#testConextIsParameterizedType()

Project: guava
Source File: TypeTokenResolutionTest.java
View license
public void testConextIsParameterizedType() throws Exception {
    class Context {

        // used by reflection
        @SuppressWarnings("unused")
        Map<String, Integer> returningMap() {
            throw new AssertionError();
        }
    }
    Type context = Context.class.getDeclaredMethod("returningMap").getGenericReturnType();
    Type keyType = Map.class.getTypeParameters()[0];
    Type valueType = Map.class.getTypeParameters()[1];
    // context is parameterized type
    assertEquals(String.class, TypeToken.of(context).resolveType(keyType).getType());
    assertEquals(Integer.class, TypeToken.of(context).resolveType(valueType).getType());
    // context is type variable
    assertEquals(keyType, TypeToken.of(keyType).resolveType(keyType).getType());
    assertEquals(valueType, TypeToken.of(valueType).resolveType(valueType).getType());
}

20. BoundedGenericMethodsTests#parameterType()

View license
/**
     * Tests whether the specified method declares a parameter with the type of
     * the type parameter.
     *
     * @param method
     *            the declaring method
     */
private void parameterType(Method method) {
    TypeVariable<Method> typeParameter = getTypeParameter(method);
    assertLenghtOne(method.getGenericParameterTypes());
    Type genericParameterType = method.getGenericParameterTypes()[0];
    assertEquals(typeParameter, genericParameterType);
    assertTrue(genericParameterType instanceof TypeVariable);
    TypeVariable<?> typeVariable = (TypeVariable<?>) genericParameterType;
    assertEquals(method, typeVariable.getGenericDeclaration());
    Type[] paramBounds = typeVariable.getBounds();
    assertLenghtOne(paramBounds);
    Type paramBound = paramBounds[0];
    assertEquals(BoundedGenericMethods.class, paramBound);
}

21. BoundedGenericMethodsTests#checkReturnType()

View license
@SuppressWarnings("unchecked")
private void checkReturnType(Method method) {
    Type genericReturnType = method.getGenericReturnType();
    assertEquals(getTypeParameter(method), genericReturnType);
    assertTrue(genericReturnType instanceof TypeVariable);
    TypeVariable<Method> returnTypeVariable = (TypeVariable<Method>) genericReturnType;
    assertEquals(method, returnTypeVariable.getGenericDeclaration());
    Type[] bounds = returnTypeVariable.getBounds();
    assertLenghtOne(bounds);
    Type bound = bounds[0];
    assertEquals(BoundedGenericMethods.class, bound);
}

22. WildcardTypeTest#checkReturnType()

Project: j2objc
Source File: WildcardTypeTest.java
View license
@SuppressWarnings("unchecked")
private void checkReturnType(Method method) {
    Type genericReturnType = method.getGenericReturnType();
    assertEquals(getTypeParameter(method), genericReturnType);
    assertTrue(genericReturnType instanceof TypeVariable);
    TypeVariable<Method> returnTypeVariable = (TypeVariable<Method>) genericReturnType;
    assertEquals(method, returnTypeVariable.getGenericDeclaration());
    Type[] bounds = returnTypeVariable.getBounds();
    assertLenghtOne(bounds);
    Type bound = bounds[0];
    assertEquals(BoundedWildcardsGenericMethods.class, bound);
}

23. ParameterConvertersBehaviour#shouldConvertCommaSeparatedValuesToListOfStrings()

View license
@Test
public void shouldConvertCommaSeparatedValuesToListOfStrings() throws IntrospectionException {
    ParameterConverter converter = new StringListConverter();
    Type listOfStrings = SomeSteps.methodFor("aMethodWithListOfStrings").getGenericParameterTypes()[0];
    Type listOfNumbers = SomeSteps.methodFor("aMethodWithListOfNumbers").getGenericParameterTypes()[0];
    Type setOfNumbers = SomeSteps.methodFor("aMethodWithSetOfNumbers").getGenericParameterTypes()[0];
    assertThat(converter.accept(listOfStrings), is(true));
    assertThat(converter.accept(listOfNumbers), is(false));
    assertThat(converter.accept(setOfNumbers), is(false));
    ensureValueIsConvertedToList(converter, listOfStrings, "a, string ", Arrays.asList("a", "string"));
    ensureValueIsConvertedToList(converter, listOfStrings, " ", Arrays.asList(new String[] {}));
}

24. Mirror#getTypeParams()

Project: nutz
Source File: Mirror.java
View license
/**
     * ??????????????????????????? null
     */
public static Type[] getTypeParams(Class<?> klass) {
    // TODO ???????????,????????
    if (klass == null || "java.lang.Object".equals(klass.getName()))
        return null;
    // ????
    Type superclass = klass.getGenericSuperclass();
    if (null != superclass && superclass instanceof ParameterizedType)
        return ((ParameterizedType) superclass).getActualTypeArguments();
    // ????
    Type[] interfaces = klass.getGenericInterfaces();
    for (Type inf : interfaces) {
        if (inf instanceof ParameterizedType) {
            return ((ParameterizedType) inf).getActualTypeArguments();
        }
    }
    return getTypeParams(klass.getSuperclass());
}

25. GenericTypeReflector#getExactParameterTypes()

Project: objectify
Source File: GenericTypeReflector.java
View license
/**
	 * Returns the exact parameter types of the given method in the given type.
	 * This may be different from <tt>m.getGenericParameterTypes()</tt> when the method was declared in a superclass,
	 * or <tt>type</tt> has a type parameter that is used in one of the parameters, or <tt>type</tt> is a raw type.
	 */
public static Type[] getExactParameterTypes(Method m, Type type) {
    Type[] parameterTypes = m.getGenericParameterTypes();
    Type exactDeclaringType = getExactSuperType(capture(type), m.getDeclaringClass());
    if (// capture(type) is not a subtype of m.getDeclaringClass()
    exactDeclaringType == null) {
        throw new IllegalArgumentException("The method " + m + " is not a member of type " + type);
    }
    Type[] result = new Type[parameterTypes.length];
    for (int i = 0; i < parameterTypes.length; i++) {
        result[i] = mapTypeParameters(parameterTypes[i], exactDeclaringType);
    }
    return result;
}

26. GenericsUtil#resolveTypeArguments()

Project: openwebbeans
Source File: GenericsUtil.java
View license
private static Type[] resolveTypeArguments(Class<?> subclass, ParameterizedType parameterizedSupertype) {
    Type genericSuperclass = getGenericSuperclass(subclass, getRawType(parameterizedSupertype));
    if (!(genericSuperclass instanceof ParameterizedType)) {
        return subclass.getTypeParameters();
    }
    ParameterizedType parameterizedSuperclass = (ParameterizedType) genericSuperclass;
    Type[] typeParameters = subclass.getTypeParameters();
    Type[] actualTypeArguments = parameterizedSupertype.getActualTypeArguments();
    return resolveTypeArguments(parameterizedSuperclass, typeParameters, actualTypeArguments);
}

27. TypesTest#testClassGenericTypeDiscovery()

Project: Resteasy
Source File: TypesTest.java
View license
@Test
public void testClassGenericTypeDiscovery() throws Exception {
    Type[] types = Types.findParameterizedTypes(ClassFooBar.class, ClassBar.class);
    for (Type t : types) {
        System.out.println(t);
    }
    Assert.assertEquals(types[0], Float.class);
    types = Types.findParameterizedTypes(ClassSub.class, ClassBar.class);
    for (Type t : types) {
        System.out.println(t);
    }
    Assert.assertEquals(types[0], Float.class);
}

28. GenericTypeReflector#getExactParameterTypes()

Project: spock
Source File: GenericTypeReflector.java
View license
public static Type[] getExactParameterTypes(Method m, Type type) {
    Type[] parameterTypes = m.getGenericParameterTypes();
    if (m.getDeclaringClass() == Object.class) {
        return parameterTypes;
    }
    Type exactDeclaringType = getExactSuperType(capture(type), m.getDeclaringClass());
    Type[] result = new Type[parameterTypes.length];
    for (int i = 0; i < parameterTypes.length; i++) {
        result[i] = mapTypeParameters(parameterTypes[i], exactDeclaringType);
    }
    return result;
}

29. GenericTypeResolver#resolveReturnTypeArgument()

View license
/**
	 * Resolve the single type argument of the given generic interface against the given
	 * target method which is assumed to return the given interface or an implementation
	 * of it.
	 * @param method the target method to check the return type of
	 * @param genericIfc the generic interface or superclass to resolve the type argument from
	 * @return the resolved parameter type of the method return type, or {@code null}
	 * if not resolvable or if the single argument is of type {@link WildcardType}.
	 */
public static Class<?> resolveReturnTypeArgument(Method method, Class<?> genericIfc) {
    Assert.notNull(method, "method must not be null");
    Type returnType = method.getReturnType();
    Type genericReturnType = method.getGenericReturnType();
    if (returnType.equals(genericIfc)) {
        if (genericReturnType instanceof ParameterizedType) {
            ParameterizedType targetType = (ParameterizedType) genericReturnType;
            Type[] actualTypeArguments = targetType.getActualTypeArguments();
            Type typeArg = actualTypeArguments[0];
            if (!(typeArg instanceof WildcardType)) {
                return (Class<?>) typeArg;
            }
        } else {
            return null;
        }
    }
    return resolveTypeArgument((Class<?>) returnType, genericIfc);
}

30. TypeUtilsTests#testWithParameterizedTypes()

Project: spring-android
Source File: TypeUtilsTests.java
View license
public void testWithParameterizedTypes() throws Exception {
    Type objectsType = getClass().getField("objects").getGenericType();
    Type openObjectsType = getClass().getField("openObjects").getGenericType();
    Type stringsType = getClass().getField("strings").getGenericType();
    assertTrue(TypeUtils.isAssignable(Object.class, objectsType));
    assertTrue(TypeUtils.isAssignable(Object.class, openObjectsType));
    assertTrue(TypeUtils.isAssignable(Object.class, stringsType));
    assertTrue(TypeUtils.isAssignable(List.class, objectsType));
    assertTrue(TypeUtils.isAssignable(List.class, openObjectsType));
    assertTrue(TypeUtils.isAssignable(List.class, stringsType));
    assertTrue(TypeUtils.isAssignable(objectsType, List.class));
    assertTrue(TypeUtils.isAssignable(openObjectsType, List.class));
    assertTrue(TypeUtils.isAssignable(stringsType, List.class));
    assertTrue(TypeUtils.isAssignable(objectsType, objectsType));
    assertTrue(TypeUtils.isAssignable(openObjectsType, openObjectsType));
    assertTrue(TypeUtils.isAssignable(stringsType, stringsType));
    assertTrue(TypeUtils.isAssignable(openObjectsType, objectsType));
    assertTrue(TypeUtils.isAssignable(openObjectsType, stringsType));
    assertFalse(TypeUtils.isAssignable(stringsType, objectsType));
    assertFalse(TypeUtils.isAssignable(objectsType, stringsType));
}

31. FormMultivaluedMapProvider#isReadable()

View license
public boolean isReadable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
    // must be a multivalued map and parameterized with Strings
    if (!(MultivaluedMap.class == type) || !(genericType instanceof ParameterizedType)) {
        return false;
    }
    ParameterizedType pType = (ParameterizedType) genericType;
    Type[] actualTypeArguments = pType.getActualTypeArguments();
    Type type1 = actualTypeArguments[0];
    Type type2 = actualTypeArguments[1];
    if (!(type1 instanceof Class<?>) || !((Class<?>) type1).equals(String.class) || !(type2 instanceof Class<?>) || !((Class<?>) type2).equals(String.class)) {
        return false;
    }
    return true;
}

32. EventTypeMetadata#extractIterableType()

Project: airlift
Source File: EventTypeMetadata.java
View license
private Class<?> extractIterableType(Method method) {
    Type[] types = getTypeParameters(Iterable.class, method.getGenericReturnType());
    if ((types == null) || (types.length != 1)) {
        addMethodError("Unable to get type parameter for iterable [%s]", method, method.getGenericReturnType());
        return null;
    }
    Type type = types[0];
    if (!(type instanceof Class)) {
        addMethodError("Iterable type parameter [%s] must be an exact type", method, type);
        return null;
    }
    if (isIterable((Class<?>) type)) {
        addMethodError("Iterable of iterable is not supported", method);
        return null;
    }
    return (Class<?>) type;
}

33. Accessor#getItemType()

Project: airline
Source File: Accessor.java
View license
private static Class<?> getItemType(String name, Type type) {
    Class<?> rawClass = getRawType(type);
    if (rawClass == null) {
        throw new ParseException("Type of option %s be an exact type", name);
    }
    if (!Collection.class.isAssignableFrom(rawClass)) {
        return rawClass;
    }
    Type[] types = getTypeParameters(Collection.class, type);
    if ((types == null) || (types.length != 1)) {
        throw new ParseException("Unable to get item type of Collection option %s", name);
    }
    Type itemType = types[0];
    if (!(itemType instanceof Class)) {
        throw new ParseException("Collection type option %s must be an exact type", name);
    }
    return (Class<?>) itemType;
}

34. CollectionTypeAdapterFactory#create()

View license
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> typeToken) {
    Type type = typeToken.getType();
    Class<? super T> rawType = typeToken.getRawType();
    if (!Collection.class.isAssignableFrom(rawType)) {
        return null;
    }
    Type elementType = $Gson$Types.getCollectionElementType(type, rawType);
    TypeAdapter<?> elementTypeAdapter = gson.getAdapter(TypeToken.get(elementType));
    ObjectConstructor<T> constructor = constructorConstructor.get(typeToken);
    // create() doesn't define a type parameter
    @SuppressWarnings({ "unchecked", "rawtypes" }) TypeAdapter<T> result = new Adapter(gson, elementType, elementTypeAdapter, constructor);
    return result;
}

35. MapTypeAdapterFactory#create()

View license
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> typeToken) {
    Type type = typeToken.getType();
    Class<? super T> rawType = typeToken.getRawType();
    if (!Map.class.isAssignableFrom(rawType)) {
        return null;
    }
    Class<?> rawTypeOfSrc = $Gson$Types.getRawType(type);
    Type[] keyAndValueTypes = $Gson$Types.getMapKeyAndValueTypes(type, rawTypeOfSrc);
    TypeAdapter<?> keyAdapter = getKeyAdapter(gson, keyAndValueTypes[0]);
    TypeAdapter<?> valueAdapter = gson.getAdapter(TypeToken.get(keyAndValueTypes[1]));
    ObjectConstructor<T> constructor = constructorConstructor.get(typeToken);
    @SuppressWarnings({ "unchecked", "rawtypes" }) // we don't define a type parameter for the key or value types
    TypeAdapter<T> result = new Adapter(gson, keyAndValueTypes[0], keyAdapter, keyAndValueTypes[1], valueAdapter, constructor);
    return result;
}

36. TypeUtils#isAssignable()

Project: Android-Next
Source File: TypeUtils.java
View license
private static boolean isAssignable(ParameterizedType lhsType, ParameterizedType rhsType) {
    if (lhsType.equals(rhsType)) {
        return true;
    }
    Type[] lhsTypeArguments = lhsType.getActualTypeArguments();
    Type[] rhsTypeArguments = rhsType.getActualTypeArguments();
    if (lhsTypeArguments.length != rhsTypeArguments.length) {
        return false;
    }
    for (int size = lhsTypeArguments.length, i = 0; i < size; ++i) {
        Type lhsArg = lhsTypeArguments[i];
        Type rhsArg = rhsTypeArguments[i];
        if (!lhsArg.equals(rhsArg) && !(lhsArg instanceof WildcardType && isAssignable((WildcardType) lhsArg, rhsArg))) {
            return false;
        }
    }
    return true;
}

37. AmountParser#doParse()

Project: aurora
Source File: AmountParser.java
View license
@Override
Amount<?, ?> doParse(ParserOracle parserOracle, String raw, List<Type> typeParams) {
    Type valueType = typeParams.get(0);
    Parser<?> parser = parserOracle.get(TypeToken.of(valueType));
    Matcher matcher = AMOUNT_PATTERN.matcher(raw);
    checkArgument(matcher.matches(), "Value '" + raw + "' must be of the format 1ns, 4mb, etc.");
    Number number = (Number) parser.parse(parserOracle, valueType, matcher.group(1));
    String unitRaw = matcher.group(2);
    Type unitType = typeParams.get(1);
    @SuppressWarnings("rawtypes") Parser<Unit> unitParser = parserOracle.get(TypeToken.of(Unit.class));
    @SuppressWarnings("rawtypes") Unit unit = unitParser.parse(parserOracle, unitType, unitRaw);
    checkArgument(unit.getClass() == unitType, String.format("Unit type (%s) does not match argument type (%s).", unit.getClass(), unitType));
    return create(valueType, number, unit);
}

38. MapParser#doParse()

Project: aurora
Source File: MapParser.java
View license
@SuppressWarnings("unchecked")
@Override
Map<?, ?> doParse(ParserOracle parserOracle, String raw, List<Type> typeParams) {
    Type keyType = typeParams.get(0);
    Parser<?> keyParser = parserOracle.get(TypeToken.of(keyType));
    Type valueType = typeParams.get(1);
    Parser<?> valueParser = parserOracle.get(TypeToken.of(valueType));
    ImmutableMap.Builder<Object, Object> map = ImmutableMap.builder();
    for (String keyAndValue : Parsers.MULTI_VALUE_SPLITTER.split(raw)) {
        List<String> fields = ImmutableList.copyOf(KEY_VALUE_SPLITTER.split(keyAndValue));
        checkArgument(fields.size() == 2, "Failed to parse key/value pair " + keyAndValue);
        map.put(keyParser.parse(parserOracle, keyType, fields.get(0)), valueParser.parse(parserOracle, valueType, fields.get(1)));
    }
    return map.build();
}

39. MultimapParser#doParse()

Project: aurora
Source File: MultimapParser.java
View license
@SuppressWarnings("unchecked")
@Override
Multimap<?, ?> doParse(ParserOracle parserOracle, String raw, List<Type> typeParams) {
    Type keyType = typeParams.get(0);
    Parser<?> keyParser = parserOracle.get(TypeToken.of(keyType));
    Type valueType = typeParams.get(1);
    Parser<?> valueParser = parserOracle.get(TypeToken.of(valueType));
    ImmutableMultimap.Builder<Object, Object> multimapBuilder = ImmutableMultimap.builder();
    for (String keyAndValue : Parsers.MULTI_VALUE_SPLITTER.split(raw)) {
        List<String> fields = ImmutableList.copyOf(KEY_VALUE_SPLITTER.split(keyAndValue));
        checkArgument(fields.size() == 2, "Failed to parse key/value pair: " + keyAndValue);
        multimapBuilder.put(keyParser.parse(parserOracle, keyType, fields.get(0)), valueParser.parse(parserOracle, valueType, fields.get(1)));
    }
    return multimapBuilder.build();
}

40. PairParser#doParse()

Project: aurora
Source File: PairParser.java
View license
@Override
Pair<?, ?> doParse(ParserOracle parserOracle, String raw, List<Type> typeParams) {
    Type leftType = typeParams.get(0);
    Parser<?> leftParser = parserOracle.get(TypeToken.of(leftType));
    Type rightType = typeParams.get(1);
    Parser<?> rightParser = parserOracle.get(TypeToken.of(rightType));
    List<String> parts = ImmutableList.copyOf(Parsers.MULTI_VALUE_SPLITTER.split(raw));
    checkArgument(parts.size() == 2, "Only two values may be specified for a pair, you gave " + parts.size());
    return Pair.of(leftParser.parse(parserOracle, leftType, parts.get(0)), rightParser.parse(parserOracle, rightType, parts.get(1)));
}

41. ReflectUtils#getClassGenricType()

Project: AutoLoadCache
Source File: ReflectUtils.java
View license
/**
     * ?????????????
     * @param clazz ????
     * @param index ??
     */
public static Class<?> getClassGenricType(final Class<?> clazz, final int index) {
    Type genType = clazz.getGenericSuperclass();
    if (!(genType instanceof ParameterizedType)) {
        return Object.class;
    }
    Type[] params = ((ParameterizedType) genType).getActualTypeArguments();
    if (index >= params.length || index < 0) {
        return Object.class;
    }
    if (!(params[index] instanceof Class)) {
        return Object.class;
    }
    return (Class<?>) params[index];
}

42. TypeUtils#isAssignable()

Project: bboss
Source File: TypeUtils.java
View license
private static boolean isAssignable(ParameterizedType lhsType, ParameterizedType rhsType) {
    if (lhsType.equals(rhsType)) {
        return true;
    }
    Type[] lhsTypeArguments = lhsType.getActualTypeArguments();
    Type[] rhsTypeArguments = rhsType.getActualTypeArguments();
    if (lhsTypeArguments.length != rhsTypeArguments.length) {
        return false;
    }
    for (int size = lhsTypeArguments.length, i = 0; i < size; ++i) {
        Type lhsArg = lhsTypeArguments[i];
        Type rhsArg = rhsTypeArguments[i];
        if (!lhsArg.equals(rhsArg) && !(lhsArg instanceof WildcardType && isAssignable((WildcardType) lhsArg, rhsArg))) {
            return false;
        }
    }
    return true;
}

43. TypeUtils#isAssignable()

Project: bboss
Source File: TypeUtils.java
View license
private static boolean isAssignable(WildcardType lhsType, Type rhsType) {
    Type[] upperBounds = lhsType.getUpperBounds();
    Type[] lowerBounds = lhsType.getLowerBounds();
    for (int size = upperBounds.length, i = 0; i < size; ++i) {
        if (!isAssignable(upperBounds[i], rhsType)) {
            return false;
        }
    }
    for (int size = lowerBounds.length, i = 0; i < size; ++i) {
        if (!isAssignable(rhsType, lowerBounds[i])) {
            return false;
        }
    }
    return true;
}

44. CPPRuntimeTest#testType()

Project: BridJ
Source File: CPPRuntimeTest.java
View license
@Test
public void testType() {
    int[] targsCount = new int[1];
    Object[] targsAndArgs = new Object[] { int.class, double.class };
    Type expected = CPPType.getCPPType(Temp.class, int.class, double.class);
    Type actual = runtime.getType(Temp.class, targsAndArgs, targsCount);
    assertEquals(expected, actual);
    assertEquals(2, targsCount[0]);
    actual = runtime.getType(Temp.class, targsAndArgs, null);
    assertEquals(expected, actual);
}

45. Types#getContainerClass()

Project: buck
Source File: Types.java
View license
/**
   * @return The raw type of the {@link Collection} a field represents, even if contained in an
   *    {@link Optional}, but without the ParameterizedType information.
   */
@SuppressWarnings("unchecked")
@Nullable
public static Class<? extends Collection<?>> getContainerClass(Field field) {
    Type type = getFirstNonOptionalType(field);
    if (!(type instanceof ParameterizedType)) {
        return null;
    }
    Type rawType = ((ParameterizedType) type).getRawType();
    if (!(rawType instanceof Class)) {
        return null;
    }
    Class<?> clazz = (Class<?>) rawType;
    if (!(Collection.class.isAssignableFrom(clazz))) {
        return null;
    }
    return (Class<? extends Collection<?>>) clazz;
}

46. TypeToken#isAssignableToParameterizedType()

Project: cdap
Source File: TypeToken.java
View license
private static boolean isAssignableToParameterizedType(Type from, ParameterizedType to) {
    Class<?> matchedClass = getRawType(to);
    if (!matchedClass.isAssignableFrom(getRawType(from))) {
        return false;
    }
    Type[] typeParams = matchedClass.getTypeParameters();
    Type[] toTypeArgs = to.getActualTypeArguments();
    TypeToken<?> fromTypeToken = of(from);
    for (int i = 0; i < typeParams.length; i++) {
        // If "to" is "List<? extends CharSequence>"
        // and "from" is StringArrayList,
        // First step is to figure out StringArrayList "is-a" List<E> and <E> is
        // String.
        // typeParams[0] is E and fromTypeToken.get(typeParams[0]) will resolve to
        // String.
        // String is then matched against <? extends CharSequence>.
        Type fromTypeArg = fromTypeToken.resolveType(typeParams[i]).runtimeType;
        if (!matchTypeArgument(fromTypeArg, toTypeArgs[i])) {
            return false;
        }
    }
    return true;
}

47. AbstractProgramTwillRunnable#createProgramRunner()

View license
/**
   * Creates a {@link ProgramRunner} for the running the program in this {@link TwillRunnable}.
   */
protected ProgramRunner createProgramRunner(Injector injector) {
    Type type = TypeToken.of(getClass()).getSupertype(AbstractProgramTwillRunnable.class).getType();
    // Must be ParameterizedType
    Preconditions.checkState(type instanceof ParameterizedType, "Invalid ProgramTwillRunnable class %s. Expected to be a ParameterizedType.", getClass());
    Type programRunnerType = ((ParameterizedType) type).getActualTypeArguments()[0];
    // the ProgramRunnerType must be a Class
    Preconditions.checkState(programRunnerType instanceof Class, "ProgramRunner type is not a class: %s", programRunnerType);
    @SuppressWarnings("unchecked") Class<ProgramRunner> programRunnerClass = (Class<ProgramRunner>) programRunnerType;
    return injector.getInstance(programRunnerClass);
}

48. SparkProgramRuntimeProvider#createInstance()

View license
/**
   * Create a new instance of the given {@link Type} from the given {@link Injector}. This method
   * is doing Guice injection manually through the @Inject constructor to avoid ClassLoader leakage
   * due to the just-in-time binding map inside the Guice Injector that holds a strong reference to the type,
   * hence the ClassLoader of that type
   *
   * @param injector The Guice Injector for acquiring CDAP system instances
   * @param type the {@link Class} of the instance to create
   * @return a new instance of the given {@link Type}
   */
private <T> T createInstance(Injector injector, Type type, ClassLoader sparkClassLoader) throws Exception {
    Key<?> typeKey = Key.get(type);
    @SuppressWarnings("unchecked") Class<T> rawType = (Class<T>) typeKey.getTypeLiteral().getRawType();
    Constructor<T> constructor = findInjectableConstructor(rawType);
    constructor.setAccessible(true);
    // Acquire the instances for each parameter for the constructor
    Type[] paramTypes = constructor.getGenericParameterTypes();
    Object[] args = new Object[paramTypes.length];
    int i = 0;
    for (Type paramType : paramTypes) {
        Key<?> paramTypeKey = Key.get(paramType);
        // instance manually instead of getting through the Guice Injector to avoid ClassLoader leakage
        if (paramTypeKey.getTypeLiteral().getRawType().getClassLoader() == sparkClassLoader) {
            args[i++] = createInstance(injector, paramType, sparkClassLoader);
        } else {
            args[i++] = injector.getInstance(paramTypeKey);
        }
    }
    return constructor.newInstance(args);
}

49. TypeToken#isAssignableToParameterizedType()

Project: cdk
Source File: TypeToken.java
View license
private static boolean isAssignableToParameterizedType(Type from, ParameterizedType to) {
    Class<?> matchedClass = getRawType(to);
    if (!matchedClass.isAssignableFrom(getRawType(from))) {
        return false;
    }
    Type[] typeParams = matchedClass.getTypeParameters();
    Type[] toTypeArgs = to.getActualTypeArguments();
    TypeToken<?> fromTypeToken = of(from);
    for (int i = 0; i < typeParams.length; i++) {
        // If "to" is "List<? extends CharSequence>"
        // and "from" is StringArrayList,
        // First step is to figure out StringArrayList "is-a" List<E> and <E> is
        // String.
        // typeParams[0] is E and fromTypeToken.get(typeParams[0]) will resolve to
        // String.
        // String is then matched against <? extends CharSequence>.
        Type fromTypeArg = fromTypeToken.resolveType(typeParams[i]).runtimeType;
        if (!matchTypeArgument(fromTypeArg, toTypeArgs[i])) {
            return false;
        }
    }
    return true;
}

50. AmountParser#doParse()

Project: commons
Source File: AmountParser.java
View license
@Override
Amount<?, ?> doParse(ParserOracle parserOracle, String raw, List<Type> typeParams) {
    Type valueType = typeParams.get(0);
    Parser<?> parser = parserOracle.get(TypeToken.of(valueType));
    Matcher matcher = AMOUNT_PATTERN.matcher(raw);
    checkArgument(matcher.matches(), "Value '" + raw + "' must be of the format 1ns, 4mb, etc.");
    Number number = (Number) parser.parse(parserOracle, valueType, matcher.group(1));
    String unitRaw = matcher.group(2);
    Type unitType = typeParams.get(1);
    @SuppressWarnings("rawtypes") Parser<Unit> unitParser = parserOracle.get(TypeToken.of(Unit.class));
    @SuppressWarnings("rawtypes") Unit unit = unitParser.parse(parserOracle, unitType, unitRaw);
    checkArgument(unit.getClass() == unitType, String.format("Unit type (%s) does not match argument type (%s).", unit.getClass(), unitType));
    return create(valueType, number, unit);
}

51. MapParser#doParse()

Project: commons
Source File: MapParser.java
View license
@SuppressWarnings("unchecked")
@Override
Map<?, ?> doParse(ParserOracle parserOracle, String raw, List<Type> typeParams) {
    Type keyType = typeParams.get(0);
    Parser<?> keyParser = parserOracle.get(TypeToken.of(keyType));
    Type valueType = typeParams.get(1);
    Parser<?> valueParser = parserOracle.get(TypeToken.of(valueType));
    ImmutableMap.Builder<Object, Object> map = ImmutableMap.builder();
    for (String keyAndValue : Parsers.MULTI_VALUE_SPLITTER.split(raw)) {
        List<String> fields = ImmutableList.copyOf(KEY_VALUE_SPLITTER.split(keyAndValue));
        checkArgument(fields.size() == 2, "Failed to parse key/value pair " + keyAndValue);
        map.put(keyParser.parse(parserOracle, keyType, fields.get(0)), valueParser.parse(parserOracle, valueType, fields.get(1)));
    }
    return map.build();
}

52. MultimapParser#doParse()

Project: commons
Source File: MultimapParser.java
View license
@SuppressWarnings("unchecked")
@Override
Multimap<?, ?> doParse(ParserOracle parserOracle, String raw, List<Type> typeParams) {
    Type keyType = typeParams.get(0);
    Parser<?> keyParser = parserOracle.get(TypeToken.of(keyType));
    Type valueType = typeParams.get(1);
    Parser<?> valueParser = parserOracle.get(TypeToken.of(valueType));
    ImmutableMultimap.Builder<Object, Object> multimapBuilder = ImmutableMultimap.builder();
    for (String keyAndValue : Parsers.MULTI_VALUE_SPLITTER.split(raw)) {
        List<String> fields = ImmutableList.copyOf(KEY_VALUE_SPLITTER.split(keyAndValue));
        checkArgument(fields.size() == 2, "Failed to parse key/value pair: " + keyAndValue);
        multimapBuilder.put(keyParser.parse(parserOracle, keyType, fields.get(0)), valueParser.parse(parserOracle, valueType, fields.get(1)));
    }
    return multimapBuilder.build();
}

53. PairParser#doParse()

Project: commons
Source File: PairParser.java
View license
@Override
Pair<?, ?> doParse(ParserOracle parserOracle, String raw, List<Type> typeParams) {
    Type leftType = typeParams.get(0);
    Parser<?> leftParser = parserOracle.get(TypeToken.of(leftType));
    Type rightType = typeParams.get(1);
    Parser<?> rightParser = parserOracle.get(TypeToken.of(rightType));
    List<String> parts = ImmutableList.copyOf(Parsers.MULTI_VALUE_SPLITTER.split(raw));
    checkArgument(parts.size() == 2, "Only two values may be specified for a pair, you gave " + parts.size());
    return Pair.of(leftParser.parse(parserOracle, leftType, parts.get(0)), rightParser.parse(parserOracle, rightType, parts.get(1)));
}

54. TypeUtils#parameterizedTypeToString()

Project: commons-lang
Source File: TypeUtils.java
View license
/**
     * Format a {@link ParameterizedType} as a {@link String}.
     * @param p {@code ParameterizedType} to format
     * @return String
     * @since 3.2
     */
private static String parameterizedTypeToString(final ParameterizedType p) {
    final StringBuilder buf = new StringBuilder();
    final Type useOwner = p.getOwnerType();
    final Class<?> raw = (Class<?>) p.getRawType();
    final Type[] typeArguments = p.getActualTypeArguments();
    if (useOwner == null) {
        buf.append(raw.getName());
    } else {
        if (useOwner instanceof Class<?>) {
            buf.append(((Class<?>) useOwner).getName());
        } else {
            buf.append(useOwner.toString());
        }
        buf.append('.').append(raw.getSimpleName());
    }
    appendAllTo(buf.append('<'), ", ", typeArguments).append('>');
    return buf.toString();
}

55. TypeUtilsTest#delegateBooleanAssertion()

Project: commons-lang
Source File: TypeUtilsTest.java
View license
public void delegateBooleanAssertion(final Type[] types, final int i2, final int i1, final boolean expected) {
    final Type type1 = types[i1];
    final Type type2 = types[i2];
    final boolean isAssignable = TypeUtils.isAssignable(type2, type1);
    if (expected) {
        Assert.assertTrue("[" + i1 + ", " + i2 + "]: From " + StringEscapeUtils.escapeHtml4(String.valueOf(type2)) + " to " + StringEscapeUtils.escapeHtml4(String.valueOf(type1)), isAssignable);
    } else {
        Assert.assertFalse("[" + i1 + ", " + i2 + "]: From " + StringEscapeUtils.escapeHtml4(String.valueOf(type2)) + " to " + StringEscapeUtils.escapeHtml4(String.valueOf(type1)), isAssignable);
    }
}

56. XSQLBluePrint#getGenericType()

Project: controller
Source File: XSQLBluePrint.java
View license
public Class<?> getGenericType(ParameterizedType type) {
    Type[] typeArguments = type.getActualTypeArguments();
    for (Type typeArgument : typeArguments) {
        if (typeArgument instanceof ParameterizedType) {
            ParameterizedType pType = (ParameterizedType) typeArgument;
            return (Class<?>) pType.getRawType();
        } else if (typeArgument instanceof Class) {
            return (Class<?>) typeArgument;
        }
    }
    return null;
}

57. Reflections#getClassGenricType()

Project: cyfm
Source File: Reflections.java
View license
/**
	 * ????, ??Class????????????????.
	 * ?????, ??Object.class.
	 * 
	 * ?public UserDao extends HibernateDao<User,Long>
	 * 
	 * @param clazz clazz The class to introspect
	 * @param index the Index of the generic ddeclaration,start from 0.
	 * @return the index generic declaration, or Object.class if cannot be determined
	 */
public static Class getClassGenricType(final Class clazz, final int index) {
    Type genType = clazz.getGenericSuperclass();
    if (!(genType instanceof ParameterizedType)) {
        logger.warn(clazz.getSimpleName() + "'s superclass not ParameterizedType");
        return Object.class;
    }
    Type[] params = ((ParameterizedType) genType).getActualTypeArguments();
    if ((index >= params.length) || (index < 0)) {
        logger.warn("Index: " + index + ", Size of " + clazz.getSimpleName() + "'s Parameterized Type: " + params.length);
        return Object.class;
    }
    if (!(params[index] instanceof Class)) {
        logger.warn(clazz.getSimpleName() + " not set the actual class on superclass generic parameter");
        return Object.class;
    }
    return (Class) params[index];
}

58. ApiSurface#addExposedTypes()

Project: DataflowJavaSDK
Source File: ApiSurface.java
View license
/**
   * Adds any types exposed to this set. These will come from the (possibly absent) bounds on the
   * wildcard.
   */
private void addExposedTypes(WildcardType type, Class<?> cause) {
    visit(type);
    for (Type lowerBound : type.getLowerBounds()) {
        logger.debug("Adding exposed types from {}, which is a type lower bound on wildcard type {}", lowerBound, type);
        addExposedTypes(lowerBound, cause);
    }
    for (Type upperBound : type.getUpperBounds()) {
        logger.debug("Adding exposed types from {}, which is a type upper bound on wildcard type {}", upperBound, type);
        addExposedTypes(upperBound, cause);
    }
}

59. InjectorImpl#createProviderBinding()

Project: elassandra
Source File: InjectorImpl.java
View license
/**
     * Creates a synthetic binding to {@code Provider<T>}, i.e. a binding to the provider from
     * {@code Binding<T>}.
     */
private <T> BindingImpl<Provider<T>> createProviderBinding(Key<Provider<T>> key, Errors errors) throws ErrorsException {
    Type providerType = key.getTypeLiteral().getType();
    // If the Provider has no type parameter (raw Provider)...
    if (!(providerType instanceof ParameterizedType)) {
        throw errors.cannotInjectRawProvider().toException();
    }
    Type entryType = ((ParameterizedType) providerType).getActualTypeArguments()[0];
    // safe because T came from Key<Provider<T>>
    @SuppressWarnings("unchecked") Key<T> providedKey = (Key<T>) key.ofType(entryType);
    BindingImpl<T> delegate = getBindingOrThrow(providedKey, errors);
    return new ProviderBindingImpl<>(this, key, delegate);
}

60. InjectorImpl#createTypeLiteralBinding()

Project: elassandra
Source File: InjectorImpl.java
View license
/**
     * 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 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();
    }
    // by definition, innerType == T, so this is safe
    @SuppressWarnings("unchecked") 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, ImmutableSet.<InjectionPoint>of(), value);
}

61. InjectorImpl#createProviderBinding()

Project: elasticsearch
Source File: InjectorImpl.java
View license
/**
     * Creates a synthetic binding to {@code Provider<T>}, i.e. a binding to the provider from
     * {@code Binding<T>}.
     */
private <T> BindingImpl<Provider<T>> createProviderBinding(Key<Provider<T>> key, Errors errors) throws ErrorsException {
    Type providerType = key.getTypeLiteral().getType();
    // If the Provider has no type parameter (raw Provider)...
    if (!(providerType instanceof ParameterizedType)) {
        throw errors.cannotInjectRawProvider().toException();
    }
    Type entryType = ((ParameterizedType) providerType).getActualTypeArguments()[0];
    // safe because T came from Key<Provider<T>>
    @SuppressWarnings("unchecked") Key<T> providedKey = (Key<T>) key.ofType(entryType);
    BindingImpl<T> delegate = getBindingOrThrow(providedKey, errors);
    return new ProviderBindingImpl<>(this, key, delegate);
}

62. InjectorImpl#createTypeLiteralBinding()

Project: elasticsearch
Source File: InjectorImpl.java
View license
/**
     * 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 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();
    }
    // by definition, innerType == T, so this is safe
    @SuppressWarnings("unchecked") 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);
}

63. ReflectUtils#findParameterizedType()

Project: es
Source File: ReflectUtils.java
View license
/**
     * ????????????????
     *
     * @param clazz
     * @param index
     * @param <T>
     * @return
     */
public static <T> Class<T> findParameterizedType(Class<?> clazz, int index) {
    Type parameterizedType = clazz.getGenericSuperclass();
    //CGLUB subclass target object(??????)
    if (!(parameterizedType instanceof ParameterizedType)) {
        parameterizedType = clazz.getSuperclass().getGenericSuperclass();
    }
    if (!(parameterizedType instanceof ParameterizedType)) {
        return null;
    }
    Type[] actualTypeArguments = ((ParameterizedType) parameterizedType).getActualTypeArguments();
    if (actualTypeArguments == null || actualTypeArguments.length == 0) {
        return null;
    }
    return (Class<T>) actualTypeArguments[0];
}

64. Util#resolveLastTypeParameter()

Project: feign
Source File: Util.java
View license
/**
   * Resolves the last type parameter of the parameterized {@code supertype}, based on the {@code
   * genericContext}, into its upper bounds. <p/> Implementation copied from {@code
   * retrofit.RestMethodInfo}.
   *
   * @param genericContext Ex. {@link java.lang.reflect.Field#getGenericType()}
   * @param supertype      Ex. {@code Decoder.class}
   * @return in the example above, the type parameter of {@code Decoder}.
   * @throws IllegalStateException if {@code supertype} cannot be resolved into a parameterized type
   *                               using {@code context}.
   */
public static Type resolveLastTypeParameter(Type genericContext, Class<?> supertype) throws IllegalStateException {
    Type resolvedSuperType = Types.getSupertype(genericContext, Types.getRawType(genericContext), supertype);
    checkState(resolvedSuperType instanceof ParameterizedType, "could not resolve %s into a parameterized type %s", genericContext, supertype);
    Type[] types = ParameterizedType.class.cast(resolvedSuperType).getActualTypeArguments();
    for (int i = 0; i < types.length; i++) {
        Type type = types[i];
        if (type instanceof WildcardType) {
            types[i] = ((WildcardType) type).getUpperBounds()[0];
        }
    }
    return types[types.length - 1];
}

65. ReflectionUtil#getClassGenricType()

Project: fqms
Source File: ReflectionUtil.java
View license
/**
	 * ????, ??Class????????????????.
	 * ?????, ??Object.class.
	 * 
	 * ?public UserDao extends HibernateDao<User,Long>
	 * 
	 * @param clazz clazz The class to introspect
	 * @param index the Index of the generic ddeclaration,start from 0.
	 * @return the index generic declaration, or Object.class if cannot be determined
	 */
@SuppressWarnings("rawtypes")
public static Class getClassGenricType(final Class clazz, final int index) {
    Type genType = clazz.getGenericSuperclass();
    if (!(genType instanceof ParameterizedType)) {
        logger.warn(clazz.getSimpleName() + "'s superclass not ParameterizedType");
        return Object.class;
    }
    Type[] params = ((ParameterizedType) genType).getActualTypeArguments();
    if ((index >= params.length) || (index < 0)) {
        logger.warn("Index: " + index + ", Size of " + clazz.getSimpleName() + "'s Parameterized Type: " + params.length);
        return Object.class;
    }
    if (!(params[index] instanceof Class)) {
        logger.warn(clazz.getSimpleName() + " not set the actual class on superclass generic parameter");
        return Object.class;
    }
    return (Class) params[index];
}

66. GenericTypeResolver#extractBoundForTypeVariable()

Project: geowave
Source File: GenericTypeResolver.java
View license
/**
	 * Extracts the bound <code>Type</code> for a given {@link TypeVariable}.
	 */
static Type extractBoundForTypeVariable(TypeVariable<?> typeVariable) {
    Type[] bounds = typeVariable.getBounds();
    if (bounds.length == 0) {
        return Object.class;
    }
    Type bound = bounds[0];
    if (bound instanceof TypeVariable) {
        bound = extractBoundForTypeVariable((TypeVariable<?>) bound);
    }
    return bound;
}

67. SubtypeTester#isSubtype()

Project: guava
Source File: SubtypeTester.java
View license
/** Call this in a {@link TestSubtype} public method asserting subtype relationship. */
final <T> T isSubtype(T sub) {
    Type returnType = method.getGenericReturnType();
    Type paramType = getOnlyParameterType();
    TestSubtype spec = method.getAnnotation(TestSubtype.class);
    assertThat(TypeToken.of(paramType).isSubtypeOf(returnType)).isTrue();
    assertThat(TypeToken.of(returnType).isSupertypeOf(paramType)).isTrue();
    if (!spec.suppressGetSubtype()) {
        assertThat(getSubtype(returnType, TypeToken.of(paramType).getRawType())).isEqualTo(paramType);
    }
    if (!spec.suppressGetSupertype()) {
        assertThat(getSupertype(paramType, TypeToken.of(returnType).getRawType())).isEqualTo(returnType);
    }
    return sub;
}

68. TypesTest#testNewParameterizedTypeImmutability()

Project: guava
Source File: TypesTest.java
View license
/**
   * Working with arrays requires defensive code. Verify that we clone the
   * type array for both input and output.
   */
public void testNewParameterizedTypeImmutability() {
    Type[] typesIn = { String.class, Integer.class };
    ParameterizedType parameterizedType = Types.newParameterizedType(Map.class, typesIn);
    typesIn[0] = null;
    typesIn[1] = null;
    Type[] typesOut = parameterizedType.getActualTypeArguments();
    typesOut[0] = null;
    typesOut[1] = null;
    assertEquals(String.class, parameterizedType.getActualTypeArguments()[0]);
    assertEquals(Integer.class, parameterizedType.getActualTypeArguments()[1]);
}

69. TypeTokenResolutionTest#testGenericInterface()

Project: guava
Source File: TypeTokenResolutionTest.java
View license
public void testGenericInterface() {
    // test the 1st generic interface on the class
    Type fType = Supplier.class.getTypeParameters()[0];
    assertEquals(Integer.class, TypeToken.of(IntegerStringFunction.class).resolveType(fType).getRawType());
    // test the 2nd generic interface on the class
    Type predicateParameterType = Predicate.class.getTypeParameters()[0];
    assertEquals(new TypeToken<List<String>>() {
    }.getType(), TypeToken.of(IntegerStringFunction.class).resolveType(predicateParameterType).getType());
}

70. InjectorImpl#getProvidedKey()

Project: guice
Source File: InjectorImpl.java
View license
private static <T> Key<T> getProvidedKey(Key<Provider<T>> key, Errors errors) throws ErrorsException {
    Type providerType = key.getTypeLiteral().getType();
    // If the Provider has no type parameter (raw Provider)...
    if (!(providerType instanceof ParameterizedType)) {
        throw errors.cannotInjectRawProvider().toException();
    }
    Type entryType = ((ParameterizedType) providerType).getActualTypeArguments()[0];
    // safe because T came from Key<Provider<T>>
    @SuppressWarnings("unchecked") Key<T> providedKey = (Key<T>) key.ofType(entryType);
    return providedKey;
}

71. InjectorImpl#createTypeLiteralBinding()

Project: guice
Source File: InjectorImpl.java
View license
/**
   * 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 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();
    }
    // by definition, innerType == T, so this is safe
    @SuppressWarnings("unchecked") TypeLiteral<T> value = (TypeLiteral<T>) TypeLiteral.get(innerType);
    InternalFactory<TypeLiteral<T>> factory = new ConstantFactory<TypeLiteral<T>>(Initializables.of(value));
    return new InstanceBindingImpl<TypeLiteral<T>>(this, key, SourceProvider.UNKNOWN_SOURCE, factory, ImmutableSet.<InjectionPoint>of(), value);
}

72. AnyType#getRawType()

Project: halva
Source File: AnyType.java
View license
@SuppressWarnings("unchecked")
private static <T> Class<? super T> getRawType(Class<? extends AnyType> superType) {
    Type superclass = superType.getGenericSuperclass();
    if (superclass instanceof Class) {
        throw new RuntimeException("Missing type parameter.");
    }
    ParameterizedType parameterized = (ParameterizedType) superclass;
    Type type = canonicalize(parameterized.getActualTypeArguments()[0]);
    return (Class<? super T>) MoreTypes.getRawType(type);
}

73. ReflectionUtil#getGenericCollectionTypeOfMethodParameter()

Project: hapi-fhir
Source File: ReflectionUtil.java
View license
public static Class<?> getGenericCollectionTypeOfMethodParameter(Method theMethod, int theParamIndex) {
    Class<?> type;
    Type genericParameterType = theMethod.getGenericParameterTypes()[theParamIndex];
    if (Class.class.equals(genericParameterType)) {
        return null;
    }
    ParameterizedType collectionType = (ParameterizedType) genericParameterType;
    Type firstArg = collectionType.getActualTypeArguments()[0];
    if (ParameterizedType.class.isAssignableFrom(firstArg.getClass())) {
        ParameterizedType pt = ((ParameterizedType) firstArg);
        type = (Class<?>) pt.getRawType();
    } else {
        type = (Class<?>) firstArg;
    }
    return type;
}

74. ReflectionUtil#getGenericCollectionTypeOfMethodReturnType()

Project: hapi-fhir
Source File: ReflectionUtil.java
View license
@SuppressWarnings({ "rawtypes" })
public static Class<?> getGenericCollectionTypeOfMethodReturnType(Method theMethod) {
    Class<?> type;
    Type genericReturnType = theMethod.getGenericReturnType();
    if (!(genericReturnType instanceof ParameterizedType)) {
        return null;
    }
    ParameterizedType collectionType = (ParameterizedType) genericReturnType;
    Type firstArg = collectionType.getActualTypeArguments()[0];
    if (ParameterizedType.class.isAssignableFrom(firstArg.getClass())) {
        ParameterizedType pt = ((ParameterizedType) firstArg);
        type = (Class<?>) pt.getRawType();
    } else if (firstArg instanceof TypeVariable<?>) {
        Type decl = ((TypeVariable) firstArg).getBounds()[0];
        return (Class<?>) decl;
    } else if (firstArg instanceof WildcardType) {
        Type decl = ((WildcardType) firstArg).getUpperBounds()[0];
        return (Class<?>) decl;
    } else {
        type = (Class<?>) firstArg;
    }
    return type;
}

75. ReflectionHelper#typeOf()

View license
/**
	 * Returns the type of the parameter of the given method with the given parameter index.
	 *
	 * @param executable The executable of interest.
	 * @param parameterIndex The index of the parameter for which the type should be returned.
	 *
	 * @return The erased type.
	 */
public static Type typeOf(ExecutableElement executable, int parameterIndex) {
    Type[] genericParameterTypes = executable.getGenericParameterTypes();
    // getGenericParameterTypes() doesn't return synthetic parameters; in this case fall back to getParameterTypes()
    if (parameterIndex >= genericParameterTypes.length) {
        genericParameterTypes = executable.getParameterTypes();
    }
    Type type = genericParameterTypes[parameterIndex];
    if (type instanceof TypeVariable) {
        type = TypeHelper.getErasedType(type);
    }
    return type;
}

76. TypeHelper#getResolvedInterfaces()

Project: hibernate-validator
Source File: TypeHelper.java
View license
private static Type[] getResolvedInterfaces(Type type) {
    Contracts.assertNotNull(type, "type");
    Class<?> rawType = getErasedReferenceType(type);
    Type[] interfaces = rawType.getGenericInterfaces();
    Type[] resolvedInterfaces = new Type[interfaces.length];
    for (int i = 0; i < interfaces.length; i++) {
        resolvedInterfaces[i] = resolveTypeVariables(interfaces[i], type);
    }
    return resolvedInterfaces;
}

77. TypeHelper#extractType()

Project: hibernate-validator
Source File: TypeHelper.java
View license
private static Type extractType(Class<? extends ConstraintValidator<?, ?>> validator) {
    Map<Type, Type> resolvedTypes = newHashMap();
    Type constraintValidatorType = resolveTypes(resolvedTypes, validator);
    //we now have all bind from a type to its resolution at one level
    Type validatorType = ((ParameterizedType) constraintValidatorType).getActualTypeArguments()[VALIDATOR_TYPE_INDEX];
    if (validatorType == null) {
        throw log.getNullIsAnInvalidTypeForAConstraintValidatorException();
    } else if (validatorType instanceof GenericArrayType) {
        validatorType = TypeHelper.getArrayType(TypeHelper.getComponentType(validatorType));
    }
    while (resolvedTypes.containsKey(validatorType)) {
        validatorType = resolvedTypes.get(validatorType);
    }
    //FIXME raise an exception if validatorType is not a class
    return validatorType;
}

78. TypeHelper#resolveTypeForClassAndHierarchy()

Project: hibernate-validator
Source File: TypeHelper.java
View license
private static Type resolveTypeForClassAndHierarchy(Map<Type, Type> resolvedTypes, Class<?> clazz) {
    Type returnedType = resolveTypes(resolvedTypes, clazz.getGenericSuperclass());
    if (returnedType != null) {
        return returnedType;
    }
    for (Type genericInterface : clazz.getGenericInterfaces()) {
        returnedType = resolveTypes(resolvedTypes, genericInterface);
        if (returnedType != null) {
            return returnedType;
        }
    }
    return null;
}

79. TypeHelper#isWildcardTypeAssignable()

Project: hibernate-validator
Source File: TypeHelper.java
View license
private static boolean isWildcardTypeAssignable(WildcardType supertype, Type type) {
    for (Type upperBound : supertype.getUpperBounds()) {
        if (!isAssignable(upperBound, type)) {
            return false;
        }
    }
    for (Type lowerBound : supertype.getLowerBounds()) {
        if (!isAssignable(type, lowerBound)) {
            return false;
        }
    }
    return true;
}

80. TypeHelper#isSuperAssignable()

Project: hibernate-validator
Source File: TypeHelper.java
View license
private static boolean isSuperAssignable(Type supertype, Type type) {
    Type superclass = getResolvedSuperclass(type);
    if (superclass != null && isAssignable(supertype, superclass)) {
        return true;
    }
    for (Type interphace : getResolvedInterfaces(type)) {
        if (isAssignable(supertype, interphace)) {
            return true;
        }
    }
    return false;
}

81. Types#getParameterUpperBound()

Project: HttpService
Source File: Types.java
View license
public static Type getParameterUpperBound(int index, ParameterizedType type) {
    Type[] types = type.getActualTypeArguments();
    if (types.length <= index) {
        throw new IllegalArgumentException("Expected at least " + index + " type argument(s) but got: " + Arrays.toString(types));
    }
    Type paramType = types[index];
    if (paramType instanceof WildcardType) {
        return ((WildcardType) paramType).getUpperBounds()[0];
    }
    return paramType;
}

82. ApiSurface#addExposedTypes()

Project: incubator-beam
Source File: ApiSurface.java
View license
/**
   * Adds any types exposed to this set. These will come from the (possibly absent) bounds on the
   * wildcard.
   */
private void addExposedTypes(WildcardType type, Class<?> cause) {
    visit(type);
    for (Type lowerBound : type.getLowerBounds()) {
        logger.debug("Adding exposed types from {}, which is a type lower bound on wildcard type {}", lowerBound, type);
        addExposedTypes(lowerBound, cause);
    }
    for (Type upperBound : type.getUpperBounds()) {
        logger.debug("Adding exposed types from {}, which is a type upper bound on wildcard type {}", upperBound, type);
        addExposedTypes(upperBound, cause);
    }
}

83. DomInvocationHandler#createConverter()

View license
@NotNull
private Converter createConverter(final JavaMethod method) {
    final Type returnType = method.getGenericReturnType();
    final Type type = returnType == void.class ? method.getGenericParameterTypes()[0] : returnType;
    final Class parameter = DomUtil.substituteGenericType(type, myType);
    if (parameter == null) {
        LOG.error(type + " " + myType);
    }
    Converter converter = getConverter(new AnnotatedElement() {

        @Override
        public <T extends Annotation> T getAnnotation(Class<T> annotationClass) {
            return myInvocationCache.getMethodAnnotation(method, annotationClass);
        }
    }, parameter);
    if (converter == null && type instanceof TypeVariable) {
        converter = getConverter(this, DomUtil.getGenericValueParameter(myType));
    }
    if (converter == null) {
        converter = myManager.getConverterManager().getConverterByClass(parameter);
    }
    if (converter == null) {
        throw new AssertionError("No converter specified: String<->" + parameter.getName() + "; method=" + method + "; place=" + myChildDescription);
    }
    return converter;
}

84. FieldTest#test_getGenericType()

Project: j2objc
Source File: FieldTest.java
View license
// Disabled, as j2objc creates different synthetic fields than Java compilers.
//    public void test_isSynthetic() throws Exception {
//        Field[] fields = TestClass.Inner.class.getDeclaredFields();
//        assertEquals("Not exactly one field returned", 1, fields.length);
//
//        assertTrue("Enum constant not recognized", fields[0].isSynthetic());
//
//        Field field = TestEnum.class.getDeclaredField("field");
//        assertFalse("Non synthetic field wrongly stated as synthetic", field
//                .isSynthetic());
//
//        field = TestClass.class.getDeclaredField("annotatedField");
//        assertFalse("Non synthetic field wrongly stated as synthetic", field
//                .isSynthetic());
//    }
public void test_getGenericType() throws Exception {
    Field field = GenericField.class.getDeclaredField("field");
    Type type = field.getGenericType();
    @SuppressWarnings("unchecked") TypeVariable typeVar = (TypeVariable) type;
    assertEquals("Wrong type name returned", "S", typeVar.getName());
    Field boundedField = GenericField.class.getDeclaredField("boundedField");
    Type boundedType = boundedField.getGenericType();
    @SuppressWarnings("unchecked") TypeVariable boundedTypeVar = (TypeVariable) boundedType;
    assertEquals("Wrong type name returned", "T", boundedTypeVar.getName());
    assertEquals("More than one bound found", 1, boundedTypeVar.getBounds().length);
    assertEquals("Wrong bound returned", Number.class, boundedTypeVar.getBounds()[0]);
}

85. GenericArrayTypeTest#testGetGenericComponentType()

Project: j2objc
Source File: GenericArrayTypeTest.java
View license
public void testGetGenericComponentType() throws Exception {
    @SuppressWarnings("unchecked") Class<? extends A> clazz = GenericArrayTypeTest.A.class;
    Field field = clazz.getDeclaredField("array");
    Type genericType = field.getGenericType();
    assertInstanceOf(GenericArrayType.class, genericType);
    Type componentType = ((GenericArrayType) genericType).getGenericComponentType();
    assertEquals(getTypeParameter(clazz), componentType);
    assertInstanceOf(TypeVariable.class, componentType);
    TypeVariable<?> componentTypeVariable = (TypeVariable<?>) componentType;
    assertEquals("T", componentTypeVariable.getName());
    assertEquals(clazz, componentTypeVariable.getGenericDeclaration());
}

86. GenericArrayTypeTest#testParameterizedComponentType()

Project: j2objc
Source File: GenericArrayTypeTest.java
View license
public void testParameterizedComponentType() throws Exception {
    @SuppressWarnings("unchecked") Class<? extends B> clazz = GenericArrayTypeTest.B.class;
    Field field = clazz.getDeclaredField("array");
    Type genericType = field.getGenericType();
    assertInstanceOf(GenericArrayType.class, genericType);
    GenericArrayType arrayType = (GenericArrayType) genericType;
    Type componentType = arrayType.getGenericComponentType();
    assertInstanceOf(ParameterizedType.class, componentType);
    ParameterizedType parameteriezdType = (ParameterizedType) componentType;
    assertEquals(clazz, parameteriezdType.getRawType());
    assertEquals(clazz.getTypeParameters()[0], parameteriezdType.getActualTypeArguments()[0]);
}

87. ParameterizedTypeTest#testStringParameterizedSuperClass()

Project: j2objc
Source File: ParameterizedTypeTest.java
View license
public void testStringParameterizedSuperClass() {
    Class<? extends B> clazz = B.class;
    Type genericSuperclass = clazz.getGenericSuperclass();
    assertInstanceOf(ParameterizedType.class, genericSuperclass);
    ParameterizedType parameterizedType = (ParameterizedType) genericSuperclass;
    assertEquals(ParameterizedTypeTest.class, parameterizedType.getOwnerType());
    assertEquals(A.class, parameterizedType.getRawType());
    Type[] actualTypeArguments = parameterizedType.getActualTypeArguments();
    assertLenghtOne(actualTypeArguments);
    assertEquals(String.class, actualTypeArguments[0]);
}

88. ParameterizedTypeTest#testTypeParameterizedSuperClass()

Project: j2objc
Source File: ParameterizedTypeTest.java
View license
public void testTypeParameterizedSuperClass() {
    Class<? extends D> clazz = D.class;
    Type genericSuperclass = clazz.getGenericSuperclass();
    assertInstanceOf(ParameterizedType.class, genericSuperclass);
    ParameterizedType parameterizedType = (ParameterizedType) genericSuperclass;
    assertEquals(ParameterizedTypeTest.class, parameterizedType.getOwnerType());
    assertEquals(C.class, parameterizedType.getRawType());
    Type[] actualTypeArguments = parameterizedType.getActualTypeArguments();
    assertLenghtOne(actualTypeArguments);
    assertEquals(getTypeParameter(D.class), actualTypeArguments[0]);
}

89. ClassTest#testGetGenericSuperclass()

Project: j2objc
Source File: ClassTest.java
View license
public void testGetGenericSuperclass() throws Exception {
    Class<?> cls = SubParameterizedClass.class;
    Type genericSuperclass = cls.getGenericSuperclass();
    assertTrue(genericSuperclass instanceof ParameterizedType);
    ParameterizedType pType = (ParameterizedType) genericSuperclass;
    assertEquals(ParameterizedClass.class, pType.getRawType());
    Type[] typeArgs = pType.getActualTypeArguments();
    assertEquals(2, typeArgs.length);
    assertEquals(String.class, typeArgs[0]);
    assertTrue(typeArgs[1] instanceof TypeVariable);
    assertEquals("C", ((TypeVariable) typeArgs[1]).getName());
}

90. ParameterConvertersBehaviour#shouldConvertCommaSeparatedValuesToListOfNumbersWithDefaultFormat()

View license
@SuppressWarnings("unchecked")
@Test
public void shouldConvertCommaSeparatedValuesToListOfNumbersWithDefaultFormat() throws ParseException, IntrospectionException {
    ParameterConverter converter = new NumberListConverter();
    Type listOfNumbers = SomeSteps.methodFor("aMethodWithListOfNumbers").getGenericParameterTypes()[0];
    Type setOfNumbers = SomeSteps.methodFor("aMethodWithSetOfNumbers").getGenericParameterTypes()[0];
    assertThat(converter.accept(listOfNumbers), is(true));
    assertThat(converter.accept(setOfNumbers), is(false));
    List<Number> list = (List<Number>) converter.convertValue("3, 0.5, 6.1f, 8.00", listOfNumbers);
    NumberFormat numberFormat = NumberFormat.getInstance(ParameterConverters.DEFAULT_NUMBER_FORMAT_LOCAL);
    assertThat(list.get(0), equalTo(numberFormat.parse("3")));
    assertThat(list.get(1), equalTo(numberFormat.parse("0.5")));
    assertThat(list.get(2), equalTo(numberFormat.parse("6.1f")));
    assertThat(list.get(3), equalTo(numberFormat.parse("8.00")));
}

91. JohnzonParameterizedType#findUserParameterizedType()

View license
private ParameterizedType findUserParameterizedType() {
    final Type genericSuperclass = getClass().getGenericSuperclass();
    if (!ParameterizedType.class.isInstance(genericSuperclass)) {
        throw new IllegalArgumentException("raw can be null only for children classes");
    }
    // our type, then unwrap it
    final ParameterizedType pt = ParameterizedType.class.cast(genericSuperclass);
    final Type userType = pt.getActualTypeArguments()[0];
    if (!ParameterizedType.class.isInstance(userType)) {
        throw new IllegalArgumentException("You need to pass a parameterized type to Johnzon*Types");
    }
    return ParameterizedType.class.cast(userType);
}

92. ArrayIT#arraysCanBeMultiDimensional()

Project: jsonschema2pojo
Source File: ArrayIT.java
View license
@Test
public void arraysCanBeMultiDimensional() throws NoSuchMethodException {
    Method getterMethod = classWithArrayProperties.getMethod("getMultiDimensionalArray");
    // assert List
    assertThat(getterMethod.getReturnType().getName(), is(List.class.getName()));
    assertThat(getterMethod.getGenericReturnType(), is(instanceOf(ParameterizedType.class)));
    // assert List<List>
    Type genericType = ((ParameterizedType) getterMethod.getGenericReturnType()).getActualTypeArguments()[0];
    assertThat(genericType, is(instanceOf(ParameterizedType.class)));
    assertThat(((Class<?>) ((ParameterizedType) genericType).getRawType()).getName(), is(List.class.getName()));
    // assert List<List<Object>>
    Type itemsType = ((ParameterizedType) genericType).getActualTypeArguments()[0];
    assertThat(itemsType, is(instanceOf(Class.class)));
    assertThat(((Class<?>) itemsType).getName(), is(Object.class.getName()));
}

93. OnColumnsRowRenderer#inferGenericType()

Project: libreplan
Source File: OnColumnsRowRenderer.java
View license
private static <T> Class<T> inferGenericType(ICellForDetailItemRenderer<?, T> renderer) {
    ParameterizedType parametrizedType = findRenderererInterfaceType(renderer);
    Type[] actualTypeArguments = parametrizedType.getActualTypeArguments();
    final int genericTypePosition = 1;
    Type type = actualTypeArguments[genericTypePosition];
    if (!isActualType(type)) {
        informCannotBeInferred(renderer);
    }
    return (Class<T>) actualTypeArguments[genericTypePosition];
}

94. OnColumnsRowRenderer#findRenderererInterfaceType()

Project: libreplan
Source File: OnColumnsRowRenderer.java
View license
private static ParameterizedType findRenderererInterfaceType(ICellForDetailItemRenderer<?, ?> renderer) {
    Type[] genericInterfaces = renderer.getClass().getGenericInterfaces();
    for (Type type : genericInterfaces) {
        if (isTypeForInterface(type, ICellForDetailItemRenderer.class)) {
            if (type instanceof ParameterizedType) {
                return (ParameterizedType) type;
            } else {
                informCannotBeInferred(renderer);
            }
        }
    }
    throw new RuntimeException("shouldn't reach here. Uncovered case for " + renderer);
}

95. GenericsUtils#getSuperClassGenericType()

View license
/**  
     * ????,??????????????????. ?BuyerServiceBean extends DaoSupport<Buyer>  
     *  
     * @param clazz clazz ??????,??????????
     * @param index ????????,?0??.  
     * @return ?????????, ??????ParameterizedType????????????????<code>Object.class</code>
     */
public static Class getSuperClassGenericType(Class clazz, int index) {
    //??????  
    Type genType = clazz.getGenericSuperclass();
    if (!(genType instanceof ParameterizedType)) {
        return Object.class;
    }
    //??????????????Type?????,????????????Class, ?BuyerServiceBean extends DaoSupport<Buyer,Contact>???Buyer?Contact??   
    Type[] params = ((ParameterizedType) genType).getActualTypeArguments();
    if (index >= params.length || index < 0) {
        throw new IllegalArgumentException("index " + (index < 0 ? " must > 0 " : " over total arguments"));
    }
    if (!(params[index] instanceof Class)) {
        return Object.class;
    }
    return (Class) params[index];
}

96. GenericsUtils#getMethodGenericParameterTypes()

View license
/**  
     * ????,?????????index?????????????????. ?: public void add(Map<String, Buyer> maps, List<String> names){}
     *  
     * @param method ??
     * @param index ???????
     * @return ????????????????, ??????ParameterizedType???????????????????
     */
public static List<Class> getMethodGenericParameterTypes(Method method, int index) {
    List<Class> results = new ArrayList<Class>();
    Type[] genericParameterTypes = method.getGenericParameterTypes();
    if (index >= genericParameterTypes.length || index < 0) {
        throw new IllegalArgumentException("index " + (index < 0 ? " must > 0 " : " over total arguments"));
    }
    Type genericParameterType = genericParameterTypes[index];
    if (genericParameterType instanceof ParameterizedType) {
        ParameterizedType aType = (ParameterizedType) genericParameterType;
        Type[] parameterArgTypes = aType.getActualTypeArguments();
        for (Type parameterArgType : parameterArgTypes) {
            Class parameterArgClass = (Class) parameterArgType;
            results.add(parameterArgClass);
        }
        return results;
    }
    return results;
}

97. TypeUtil#isParameterizedAssignable()

Project: logging-log4j2
Source File: TypeUtil.java
View license
private static boolean isParameterizedAssignable(final ParameterizedType lhs, final ParameterizedType rhs) {
    if (lhs.equals(rhs)) {
        // that was easy
        return true;
    }
    final Type[] lhsTypeArguments = lhs.getActualTypeArguments();
    final Type[] rhsTypeArguments = rhs.getActualTypeArguments();
    final int size = lhsTypeArguments.length;
    if (rhsTypeArguments.length != size) {
        // clearly incompatible types
        return false;
    }
    for (int i = 0; i < size; i++) {
        // verify all type arguments are assignable
        final Type lhsArgument = lhsTypeArguments[i];
        final Type rhsArgument = rhsTypeArguments[i];
        if (!lhsArgument.equals(rhsArgument) && !(lhsArgument instanceof WildcardType && isWildcardAssignable((WildcardType) lhsArgument, rhsArgument))) {
            return false;
        }
    }
    return true;
}

98. TypeResolver#resolveGenericType()

Project: modelmapper
Source File: TypeResolver.java
View license
/**
   * Resolves the generic Type for the {@code targetType} by walking the type hierarchy upwards from
   * the {@code initialType}.
   */
public static Type resolveGenericType(Type initialType, Class<?> targetType) {
    Class<?> rawType;
    if (initialType instanceof ParameterizedType)
        rawType = (Class<?>) ((ParameterizedType) initialType).getRawType();
    else
        rawType = (Class<?>) initialType;
    if (targetType.equals(rawType))
        return initialType;
    Type result;
    if (targetType.isInterface()) {
        for (Type superInterface : rawType.getGenericInterfaces()) if (superInterface != null && !superInterface.equals(Object.class))
            if ((result = resolveGenericType(superInterface, targetType)) != null)
                return result;
    }
    Type superType = rawType.getGenericSuperclass();
    if (superType != null && !superType.equals(Object.class))
        if ((result = resolveGenericType(superType, targetType)) != null)
            return result;
    return null;
}

99. TypesTest#newParameterizedTypeObjectMethods()

Project: moshi
Source File: TypesTest.java
View license
@Test
public void newParameterizedTypeObjectMethods() throws Exception {
    Type mapOfStringIntegerType = TypesTest.class.getDeclaredField("mapOfStringInteger").getGenericType();
    ParameterizedType newMapType = Types.newParameterizedType(Map.class, String.class, Integer.class);
    assertThat(newMapType).isEqualTo(mapOfStringIntegerType);
    assertThat(newMapType.hashCode()).isEqualTo(mapOfStringIntegerType.hashCode());
    assertThat(newMapType.toString()).isEqualTo(mapOfStringIntegerType.toString());
    Type arrayListOfMapOfStringIntegerType = TypesTest.class.getDeclaredField("arrayListOfMapOfStringInteger").getGenericType();
    ParameterizedType newListType = Types.newParameterizedType(ArrayList.class, newMapType);
    assertThat(newListType).isEqualTo(arrayListOfMapOfStringIntegerType);
    assertThat(newListType.hashCode()).isEqualTo(arrayListOfMapOfStringIntegerType.hashCode());
    assertThat(newListType.toString()).isEqualTo(arrayListOfMapOfStringIntegerType.toString());
}

100. GenericsUtils#getSuperClassGenricType()

Project: MousePaint
Source File: GenericsUtils.java
View license
/**
	 * ????,????Class??????????????. ?public BookManager extends
	 * GenricManager<Book>
	 * 
	 * @param clazz
	 *            clazz The class to introspect
	 * @param index
	 *            the Index of the generic ddeclaration,start from 0.
	 */
public static Class getSuperClassGenricType(Class clazz, int index) throws IndexOutOfBoundsException {
    Type genType = clazz.getGenericSuperclass();
    if (!(genType instanceof ParameterizedType)) {
        return Object.class;
    }
    Type[] params = ((ParameterizedType) genType).getActualTypeArguments();
    if (index >= params.length || index < 0) {
        return Object.class;
    }
    if (!(params[index] instanceof Class)) {
        return Object.class;
    }
    return (Class) params[index];
}