java.lang.reflect.TypeVariable Java Examples

The following examples show how to use java.lang.reflect.TypeVariable. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: Types.java    From keycloak with Apache License 2.0 6 votes vote down vote up
private static Type[] extractTypeVariables(Map<String, Type> typeVarMap, Type[] types)
{
    for (int j = 0; j < types.length; j++)
    {
        if (types[j] instanceof TypeVariable)
        {
            TypeVariable tv = (TypeVariable) types[j];
            types[j] = typeVarMap.get(tv.getName());
        }
        else
        {
            types[j] = types[j];
        }
    }
    return types;
}
 
Example #2
Source File: PolymorphicTypeAdapter.java    From rockscript with Apache License 2.0 6 votes vote down vote up
/** creates a map that maps generic type argument names to type tokens */
private static Map<String, TypeToken> getActualTypeArguments(TypeToken<?> typeToken) {
  Class<?> rawClass = typeToken.getRawType();
  Type type = typeToken.getType();
  TypeVariable<? extends Class<?>>[] typeParameters = rawClass.getTypeParameters();
  if (typeParameters==null || !(type instanceof ParameterizedType)) {
    return null;
  }
  Map<String, TypeToken> genericTypes = new HashMap<>();
  ParameterizedType parameterizedType = (ParameterizedType) type;
  Type[] actualTypeArguments = parameterizedType.getActualTypeArguments();
  for (int i=0; i<typeParameters.length; i++) {
    String typeParameterName = typeParameters[i].getName();
    TypeToken<?> actualType = TypeToken.get(actualTypeArguments[i]);
    genericTypes.put(typeParameterName, actualType);
  }
  return genericTypes;
}
 
Example #3
Source File: TypeToken.java    From codebuff with BSD 2-Clause "Simplified" License 6 votes vote down vote up
/**
 * Returns the generic form of {@code superclass}. For example, if this is
 * {@code ArrayList<String>}, {@code Iterable<String>} is returned given the input
 * {@code Iterable.class}.
 */


public final TypeToken<? super T> getSupertype(Class<? super T> superclass) {
  checkArgument(this.someRawTypeIsSubclassOf(superclass), "%s is not a super class of %s", superclass, this);
  if (runtimeType instanceof TypeVariable) {
    return getSupertypeFromUpperBounds(superclass, ((TypeVariable<?>) runtimeType).getBounds());
  }
  if (runtimeType instanceof WildcardType) {
    return getSupertypeFromUpperBounds(superclass, ((WildcardType) runtimeType).getUpperBounds());
  }
  if (superclass.isArray()) {
    return getArraySupertype(superclass);
  }
  @SuppressWarnings("unchecked") // resolved supertype
  TypeToken<? super T> supertype = (TypeToken<? super T>) resolveSupertype(toGenericType(superclass).runtimeType);
  return supertype;
}
 
Example #4
Source File: TypeFactory.java    From easy-mapper with Apache License 2.0 6 votes vote down vote up
/**
 * Return the Type for the given java.lang.reflect.Type, either for a
 * ParameterizedType or a Class instance
 *
 * @param type
 *
 * @return the resolved Type instance
 */
public static <T> Type<T> valueOf(final java.lang.reflect.Type type) {
    if (type instanceof Type) {
        return (Type<T>) type;
    } else if (type instanceof ParameterizedType) {
        return valueOf((ParameterizedType) type);
    } else if (type instanceof Class) {
        return valueOf((Class<T>) type);
    } else if (type instanceof TypeVariable) {
        return valueOf((TypeVariable<?>) type);
    } else if (type instanceof WildcardType) {
        return valueOf((WildcardType) type);
    } else {
        throw new IllegalArgumentException(type + " is an unsupported type");
    }
}
 
Example #5
Source File: TypeHelper.java    From SimpleFlatMapper with MIT License 6 votes vote down vote up
public static Type resolveTypeVariable(Type type, TypeVariable t) {
	TypeVariable<Class<Object>>[] typeParameters = TypeHelper.toClass(type).getTypeParameters();

	for(int i = 0; i < typeParameters.length; i++) {
		TypeVariable<Class<Object>> typeVariable = typeParameters[i];
		if (typeVariable.getName().equals(t.getName())) {
			if (type instanceof ParameterizedType) {
				return ((ParameterizedType) type).getActualTypeArguments()[i];
			} else {
				return Object.class;
			}
		}
	}
	if (typeParameters.length == 1 && type instanceof ParameterizedType && ((ParameterizedType) type).getActualTypeArguments().length == 1) {
		return ((ParameterizedType) type).getActualTypeArguments()[0];
	}
	return Object.class;
}
 
Example #6
Source File: ResolvableType.java    From dolphin with Apache License 2.0 6 votes vote down vote up
private ResolvableType resolveVariable(TypeVariable<?> variable) {
	if (this.type instanceof TypeVariable) {
		return resolveType().resolveVariable(variable);
	}
	if (this.type instanceof ParameterizedType) {
		ParameterizedType parameterizedType = (ParameterizedType) this.type;
		TypeVariable<?>[] variables = resolve().getTypeParameters();
		for (int i = 0; i < variables.length; i++) {
			if (ObjectUtils.nullSafeEquals(variables[i].getName(), variable.getName())) {
				Type actualType = parameterizedType.getActualTypeArguments()[i];
				return forType(actualType, this.variableResolver);
			}
		}
		if (parameterizedType.getOwnerType() != null) {
			return forType(parameterizedType.getOwnerType(), this.variableResolver).resolveVariable(variable);
		}
	}
	if (this.variableResolver != null) {
		return this.variableResolver.resolveVariable(variable);
	}
	return null;
}
 
Example #7
Source File: TypeUtils.java    From dolphin-platform with Apache License 2.0 6 votes vote down vote up
/**
 * Learn, recursively, whether any of the type parameters associated with {@code type} are bound to variables.
 *
 * @param type the type to check for type variables
 * @return boolean
 * @since 3.2
 */
private static boolean containsTypeVariables(final Type type) {
    if (type instanceof TypeVariable<?>) {
        return true;
    }
    if (type instanceof Class<?>) {
        return ((Class<?>) type).getTypeParameters().length > 0;
    }
    if (type instanceof ParameterizedType) {
        for (final Type arg : ((ParameterizedType) type).getActualTypeArguments()) {
            if (containsTypeVariables(arg)) {
                return true;
            }
        }
        return false;
    }
    if (type instanceof WildcardType) {
        final WildcardType wild = (WildcardType) type;
        return containsTypeVariables(TypeUtils.getImplicitLowerBounds(wild)[0])
                || containsTypeVariables(TypeUtils.getImplicitUpperBounds(wild)[0]);
    }
    return false;
}
 
Example #8
Source File: ExecuteMethodChecker.java    From lastaflute with Apache License 2.0 6 votes vote down vote up
protected Map<String, Class<?>> prepareJsonBeanGenericMap(Type genericReturnType, Class<?> jsonBeanType) {
    // can check: JsonResponse<LandBean<PiariBean>> landBean;
    final Type[] resopnseArgTypes = DfReflectionUtil.getGenericParameterTypes(genericReturnType);
    if (resopnseArgTypes.length > 0) { // just in case
        final Type firstGenericType = resopnseArgTypes[0];
        final Class<?> elementBeanType = DfReflectionUtil.getGenericFirstClass(firstGenericType);
        if (elementBeanType != null && mayBeJsonBeanType(elementBeanType)) { // just in case
            final Map<String, Class<?>> genericMap = new LinkedHashMap<String, Class<?>>(1); // only first generic #for_now
            final TypeVariable<?>[] typeParameters = jsonBeanType.getTypeParameters();
            if (typeParameters != null && typeParameters.length > 0) { // just in case
                genericMap.put(typeParameters[0].getName(), elementBeanType); // e.g. DATA = PiariBean.class
                return genericMap;
            }
        }
    }
    return Collections.emptyMap();
}
 
Example #9
Source File: C$Gson$Types.java    From letv with Apache License 2.0 6 votes vote down vote up
public static Class<?> getRawType(Type type) {
    if (type instanceof Class) {
        return (Class) type;
    }
    if (type instanceof ParameterizedType) {
        Type rawType = ((ParameterizedType) type).getRawType();
        C$Gson$Preconditions.checkArgument(rawType instanceof Class);
        return (Class) rawType;
    } else if (type instanceof GenericArrayType) {
        return Array.newInstance(C$Gson$Types.getRawType(((GenericArrayType) type).getGenericComponentType()), 0).getClass();
    } else {
        if (type instanceof TypeVariable) {
            return Object.class;
        }
        if (type instanceof WildcardType) {
            return C$Gson$Types.getRawType(((WildcardType) type).getUpperBounds()[0]);
        }
        throw new IllegalArgumentException("Expected a Class, ParameterizedType, or GenericArrayType, but <" + type + "> is of type " + (type == null ? "null" : type.getClass().getName()));
    }
}
 
Example #10
Source File: BridgeMethodResolverTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
@Deprecated
public void testCreateTypeVariableMap() throws Exception {
	Map<TypeVariable, Type> typeVariableMap = GenericTypeResolver.getTypeVariableMap(MyBar.class);
	TypeVariable<?> barT = findTypeVariable(InterBar.class, "T");
	assertEquals(String.class, typeVariableMap.get(barT));

	typeVariableMap = GenericTypeResolver.getTypeVariableMap(MyFoo.class);
	TypeVariable<?> fooT = findTypeVariable(Foo.class, "T");
	assertEquals(String.class, typeVariableMap.get(fooT));

	typeVariableMap = GenericTypeResolver.getTypeVariableMap(ExtendsEnclosing.ExtendsEnclosed.ExtendsReallyDeepNow.class);
	TypeVariable<?> r = findTypeVariable(Enclosing.Enclosed.ReallyDeepNow.class, "R");
	TypeVariable<?> s = findTypeVariable(Enclosing.Enclosed.class, "S");
	TypeVariable<?> t = findTypeVariable(Enclosing.class, "T");
	assertEquals(Long.class, typeVariableMap.get(r));
	assertEquals(Integer.class, typeVariableMap.get(s));
	assertEquals(String.class, typeVariableMap.get(t));
}
 
Example #11
Source File: SpecimenType.java    From jfixture with MIT License 6 votes vote down vote up
private static SpecimenTypeFields getFields(Type type, List<Type> recursiveGenericsGuard) {
    if(type instanceof SpecimenType) return getSpecimenTypeFields((SpecimenType) type);
    if(type instanceof Class) return getFieldsForClassType((Class)type, recursiveGenericsGuard);
    if(type instanceof ParameterizedType) return getParameterizedTypeFields((ParameterizedType) type, recursiveGenericsGuard);
    if(type instanceof GenericArrayType) return getGenericArrayFields((GenericArrayType) type);
    if(type instanceof TypeVariable) {
        // no type information for this type variable
        SpecimenTypeFields fields = new SpecimenTypeFields();
        fields.rawType = type.getClass();
        fields.genericTypeArguments = GenericTypeCollection.empty();
        return fields;
    }
    else if(type instanceof WildcardType)
        throw new UnsupportedOperationException("Wildcard types not supported");

    throw new UnsupportedOperationException(String.format("Unknown Type : %s", type.getClass()));
}
 
Example #12
Source File: FieldType.java    From jspoon with MIT License 6 votes vote down vote up
private Class<?> resolveClass(Type type, Class<?> subType) {
    if (type instanceof Class) {
        return (Class<?>) type;
    } else if (type instanceof ParameterizedType) {
        return resolveClass(((ParameterizedType) type).getRawType(), subType);
    } else if (type instanceof GenericArrayType) {
        GenericArrayType gat = (GenericArrayType) type;
        Class<?> component = resolveClass(gat.getGenericComponentType(), subType);
        return Array.newInstance(component, 0).getClass();
    } else if (type instanceof TypeVariable<?>) {
        TypeVariable<?> variable = (TypeVariable<?>) type;
        Type resolvedType = getTypeVariableMap(subType).get(variable);
        return (resolvedType == null) ? resolveClass(resolveBound(variable), subType)
                : resolveClass(resolvedType, subType);
    } else if (type instanceof WildcardType) {
        WildcardType wcType = (WildcardType) type;
        Type[] bounds = wcType.getLowerBounds().length == 0 ? wcType.getUpperBounds()
                : wcType.getLowerBounds();
        return resolveClass(bounds[0], subType);
    }
    // there are no more types in a standard JDK
    throw new IllegalArgumentException("Unknown type: " + type);
}
 
Example #13
Source File: GenericTypeResolver.java    From stategen with GNU Affero General Public License v3.0 6 votes vote down vote up
private static String getInternalGenericName(Type genericType, int i) {    
    String genericName=null;
    if (genericType instanceof ParameterizedType) { // 处理多级泛型   
        ParameterizedType subParameterizedType= (ParameterizedType) genericType;
        genericName=subParameterizedType.getTypeName();
    } else if (genericType instanceof GenericArrayType) { // 处理数组泛型  
        GenericArrayType genericArrayType= (GenericArrayType) genericType;
        genericType = genericArrayType.getGenericComponentType();
        //再递归一次
        genericName =getInternalGenericName(genericType,i); 
    } else if (genericType instanceof TypeVariable) { // 处理泛型擦拭对象     
        TypeVariable<?> typeVariable =(TypeVariable<?>) genericType;
        genericName =typeVariable.getName();
    } else if (genericType instanceof WildcardType){
        WildcardType wildcardType =((WildcardType)genericType);
        genericName=wildcardType.getTypeName();
    } 
    
    return genericName;
}
 
Example #14
Source File: GenericMetadataSupport.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
private Class<?> extractRawTypeOf(Type type) {
    if (type instanceof Class) {
        return (Class<?>) type;
    }
    if (type instanceof ParameterizedType) {
        return (Class<?>) ((ParameterizedType) type).getRawType();
    }
    if (type instanceof BoundedType) {
        return extractRawTypeOf(((BoundedType) type).firstBound());
    }
    if (type instanceof TypeVariable) {
        /*
         * If type is a TypeVariable, then it is needed to gather data elsewhere. Usually TypeVariables are declared
         * on the class definition, such as such as List<E>.
         */
        return extractRawTypeOf(contextualActualTypeParameters.get(type));
    }
    throw new MockitoException("Raw extraction not supported for : '" + type + "'");
}
 
Example #15
Source File: EnhancedType.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
private static Type validateIsSupportedType(Type type) {
    Validate.validState(type != null, "Type must not be null.");
    Validate.validState(!(type instanceof GenericArrayType),
                        "Array type %s is not supported. Use java.util.List instead of arrays.", type);
    Validate.validState(!(type instanceof TypeVariable), "Type variable type %s is not supported.", type);

    if (type instanceof WildcardType) {
        WildcardType wildcardType = (WildcardType) type;
        Validate.validState(wildcardType.getUpperBounds().length == 1 && wildcardType.getUpperBounds()[0] == Object.class,
                            "Non-Object wildcard type upper bounds are not supported.");
        Validate.validState(wildcardType.getLowerBounds().length == 0,
                            "Wildcard type lower bounds are not supported.");
    }

    return type;
}
 
Example #16
Source File: ClassTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
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());
}
 
Example #17
Source File: TypeUtils.java    From ldp4j with Apache License 2.0 5 votes vote down vote up
private String printTypeVariable(TypeVariable<?> variable, boolean qualify) {
	StringBuilder builder=new StringBuilder();
	if(qualify) {
		builder.append("<");
		builder.append(variable.getGenericDeclaration());
		builder.append("> ");
	}
	builder.append(printBounds(variable.getName(),variable.getBounds(), false));
	return builder.toString();
}
 
Example #18
Source File: TypeFactory.java    From easy-mapper with Apache License 2.0 5 votes vote down vote up
/**
 * Finds the Type value of the given TypeVariable, using recursiveBounds to
 * limit the recursion.
 *
 * @param var
 * @param recursiveBounds
 *
 * @return the resolved Type instance
 */
public static <T> Type<T> limitedValueOf(final TypeVariable<?> var,
                                         final Set<java.lang.reflect.Type> recursiveBounds) {
    if (var.getBounds().length > 0) {
        Set<Type<?>> bounds = new HashSet<Type<?>>(var.getBounds().length);
        for (int i = 0, len = var.getBounds().length; i < len; ++i) {
            bounds.add(limitedValueOf(var.getBounds()[i], recursiveBounds));
        }
        return (Type<T>) refineBounds(bounds);
    } else {
        return (Type<T>) TYPE_OF_OBJECT;
    }
}
 
Example #19
Source File: TypeUtils.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * <p> Checks if the subject type may be implicitly cast to the target type
 * following the Java generics rules. </p>
 *
 * @param type the subject type to be assigned to the target type
 * @param toType the target type
 * @param typeVarAssigns optional map of type variable assignments
 * @return <code>true</code> if <code>type</code> is assignable to <code>toType</code>.
 */
private static boolean isAssignable(final Type type, final Type toType,
        final Map<TypeVariable<?>, Type> typeVarAssigns) {
    if (toType == null || toType instanceof Class<?>) {
        return isAssignable(type, (Class<?>) toType);
    }

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

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

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

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

    throw new IllegalStateException("found an unhandled type: " + toType);
}
 
Example #20
Source File: ResolvableType.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Override
public ResolvableType resolveVariable(TypeVariable<?> variable) {
	for (int i = 0; i < this.variables.length; i++) {
		if (SerializableTypeWrapper.unwrap(this.variables[i]).equals(
				SerializableTypeWrapper.unwrap(variable))) {
			return this.generics[i];
		}
	}
	return null;
}
 
Example #21
Source File: FieldTest.java    From tk-mybatis with MIT License 5 votes vote down vote up
/**
 * @param entityClass
 */
private static Map<String, Class<?>> _getGenericTypeMap(Class<?> entityClass) {
    Map<String, Class<?>> genericMap = new HashMap<String, Class<?>>();
    if (entityClass == Object.class) {
        return genericMap;
    }
    //获取父类和泛型信息
    Class<?> superClass = entityClass.getSuperclass();
    //判断superClass
    if (superClass != null
            && !superClass.equals(Object.class)
            && (superClass.isAnnotationPresent(Entity.class)
            || (!Map.class.isAssignableFrom(superClass)
            && !Collection.class.isAssignableFrom(superClass)))) {
        if (entityClass.getGenericSuperclass() instanceof ParameterizedType) {
            Type[] types = ((ParameterizedType) entityClass.getGenericSuperclass()).getActualTypeArguments();
            TypeVariable[] typeVariables = superClass.getTypeParameters();
            if (typeVariables.length > 0) {
                for (int i = 0; i < typeVariables.length; i++) {
                    if (types[i] instanceof Class) {
                        genericMap.put(typeVariables[i].getName(), (Class<?>) types[i]);
                    }
                }
            }
        }
        genericMap.putAll(_getGenericTypeMap(superClass));
    }
    return genericMap;
}
 
Example #22
Source File: MoreTypes.java    From crate with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the declaring class of {@code typeVariable}, or {@code null} if it was not declared by
 * a class.
 */
private static Class<?> declaringClassOf(TypeVariable typeVariable) {
    GenericDeclaration genericDeclaration = typeVariable.getGenericDeclaration();
    return genericDeclaration instanceof Class
            ? (Class<?>) genericDeclaration
            : null;
}
 
Example #23
Source File: TypeUtils.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * <p>Performs a mapping of type variables.</p>
 *
 * @param <T> the generic type of the class in question
 * @param cls the class in question
 * @param parameterizedType the parameterized type
 * @param typeVarAssigns the map to be filled
 */
private static <T> void mapTypeVariablesToArguments(final Class<T> cls,
        final ParameterizedType parameterizedType, final Map<TypeVariable<?>, Type> typeVarAssigns) {
    // capture the type variables from the owner type that have assignments
    final Type ownerType = parameterizedType.getOwnerType();

    if (ownerType instanceof ParameterizedType) {
        // recursion to make sure the owner's owner type gets processed
        mapTypeVariablesToArguments(cls, (ParameterizedType) ownerType, typeVarAssigns);
    }

    // parameterizedType is a generic interface/class (or it's in the owner
    // hierarchy of said interface/class) implemented/extended by the class
    // cls. Find out which type variables of cls are type arguments of
    // parameterizedType:
    final Type[] typeArgs = parameterizedType.getActualTypeArguments();

    // of the cls's type variables that are arguments of parameterizedType,
    // find out which ones can be determined from the super type's arguments
    final TypeVariable<?>[] typeVars = getRawType(parameterizedType).getTypeParameters();

    // use List view of type parameters of cls so the contains() method can be used:
    final List<TypeVariable<Class<T>>> typeVarList = Arrays.asList(cls
            .getTypeParameters());

    for (int i = 0; i < typeArgs.length; i++) {
        final TypeVariable<?> typeVar = typeVars[i];
        final Type typeArg = typeArgs[i];

        // argument of parameterizedType is a type variable of cls
        if (typeVarList.contains(typeArg)
        // type variable of parameterizedType has an assignment in
                // the super type.
                && typeVarAssigns.containsKey(typeVar)) {
            // map the assignment to the cls's type variable
            typeVarAssigns.put((TypeVariable<?>) typeArg, typeVarAssigns.get(typeVar));
        }
    }
}
 
Example #24
Source File: TypeUtils.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
private static Type unrollVariableAssignments(TypeVariable<?> var, Map<TypeVariable<?>, Type> typeVarAssigns) {
    Type result;
    do {
        result = typeVarAssigns.get(var);
        if (result instanceof TypeVariable<?> && !result.equals(var)) {
            var = (TypeVariable<?>) result;
            continue;
        }
        break;
    } while (true);
    return result;
}
 
Example #25
Source File: IogiParametersProvider.java    From vraptor4 with Apache License 2.0 5 votes vote down vote up
private List<Target<Object>> createTargets(ControllerMethod method) {
	Method javaMethod = method.getMethod();
	List<Target<Object>> targets = new ArrayList<>();

	for (Parameter p : nameProvider.parametersFor(javaMethod)) {
		Type type = p.getParameterizedType();
		if (type instanceof TypeVariable) {
			type = extractType(method, (TypeVariable<?>) type);
		}

		targets.add(new Target<>(type, p.getName()));
	}

	return targets;
}
 
Example #26
Source File: TypeResolver.java    From quarkus with Apache License 2.0 5 votes vote down vote up
/**
 * Resolves a given type variable. This is achieved by a lookup in the {@link #resolvedTypeVariables} map.
 */
public Type resolveType(TypeVariable<?> variable) {
    Type resolvedType = this.resolvedTypeVariables.get(variable);
    if (resolvedType == null) {
        return variable; // we are not able to resolve
    }
    return resolvedType;
}
 
Example #27
Source File: m.java    From MiBandDecompiled with Apache License 2.0 5 votes vote down vote up
private Type a(Type type, Object obj)
{
    if (obj != null && (type == java/lang/Object || (type instanceof TypeVariable) || (type instanceof Class)))
    {
        type = obj.getClass();
    }
    return type;
}
 
Example #28
Source File: $Gson$Types.java    From gson with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the declaring class of {@code typeVariable}, or {@code null} if it was not declared by
 * a class.
 */
private static Class<?> declaringClassOf(TypeVariable<?> typeVariable) {
  GenericDeclaration genericDeclaration = typeVariable.getGenericDeclaration();
  return genericDeclaration instanceof Class
      ? (Class<?>) genericDeclaration
      : null;
}
 
Example #29
Source File: GenericsTrackingUtils.java    From generics-resolver with MIT License 5 votes vote down vote up
private static Map<String, Type> matchVariables(final TypeVariable declared,
                                                final Type known,
                                                final Map<String, Type> tracedRootGenerics) {
    final Map<String, Type> res = new HashMap<String, Type>();

    // lookup variable declaration for variables (e.g. T extends List<K>)
    for (Type decl : declared.getBounds()) {
        // the case: A extends B: when we know A we can't tell anything about B!
        if (decl instanceof TypeVariable) {
            continue;
        }
        final Map<String, Type> match = TypeVariableUtils.matchVariableNames(
                TypeVariableUtils.preserveVariables(decl), known);

        // check if found match is more specific then already resolved
        for (Map.Entry<String, Type> matchEntry : match.entrySet()) {
            final String name = matchEntry.getKey();
            final Type value = matchEntry.getValue();
            if (tracedRootGenerics.containsKey(name)) {
                final Type stored = tracedRootGenerics.get(name);
                if (!TypeUtils.isMoreSpecific(value, stored)) {
                    // do nothing with type
                    continue;
                }
            }
            tracedRootGenerics.put(name, value);
            res.put(name, value);
        }
    }
    return res;
}
 
Example #30
Source File: PlantRenderer.java    From Java2PlantUML with Apache License 2.0 5 votes vote down vote up
private void addClassTypeParams(StringBuilder sb, Class<?> aClass) {
    List<String> typeParams = new ArrayList<>();
    // TODO: we are leaving lower bounds out, e.g. <? super Integer>
    for (TypeVariable t : aClass.getTypeParameters()) {
        Type[] bounds = t.getBounds();
        String jointBounds = TypesHelper.getSimpleName(StringUtils.join(bounds, "&"));
        typeParams.add(t.getName() + " extends " + jointBounds);
    }
    if (0 < typeParams.size()) {
        sb.append(" <").append(StringUtils.join(typeParams, ", ")).append(">");
    }
}