Java Code Examples for java.lang.reflect.ParameterizedType#getActualTypeArguments()

The following examples show how to use java.lang.reflect.ParameterizedType#getActualTypeArguments() . 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: ClassUtils.java    From dubbox with Apache License 2.0 6 votes vote down vote up
public static Class<?> getGenericClass(Class<?> cls, int i) {
    try {
        ParameterizedType parameterizedType = ((ParameterizedType) cls.getGenericInterfaces()[0]);
        Object genericClass = parameterizedType.getActualTypeArguments()[i];
        if (genericClass instanceof ParameterizedType) { // 处理多级泛型
            return (Class<?>) ((ParameterizedType) genericClass).getRawType();
        } else if (genericClass instanceof GenericArrayType) { // 处理数组泛型
            return (Class<?>) ((GenericArrayType) genericClass).getGenericComponentType();
        } else if (genericClass != null) {
            return (Class<?>) genericClass;
        }
    } catch (Throwable e) {
    }
    if (cls.getSuperclass() != null) {
        return getGenericClass(cls.getSuperclass(), i);
    } else {
        throw new IllegalArgumentException(cls.getName() + " generic type undefined!");
    }
}
 
Example 2
Source File: MicroProfileClientProxyImpl.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Override
protected Type getGenericReturnType(Class<?> serviceCls, Method method, Class<?> returnType) {
    final Type genericReturnType = super.getGenericReturnType(serviceCls, method, returnType);
    
    if (genericReturnType instanceof ParameterizedType) {
        final ParameterizedType pt = (ParameterizedType)genericReturnType;
        if (CompletionStage.class.isAssignableFrom(InjectionUtils.getRawType(pt))) {
            final Type[] actualTypeArguments = pt.getActualTypeArguments();
            if (actualTypeArguments.length > 0 && actualTypeArguments[0] instanceof ParameterizedType) {
                return InjectionUtils.processGenericTypeIfNeeded(serviceCls, returnType, 
                    (ParameterizedType)actualTypeArguments[0]);
            } else {
                return returnType;
            }
        }
    }
    
    return genericReturnType;
}
 
Example 3
Source File: GenericsUtil.java    From redant with Apache License 2.0 6 votes vote down vote up
/**
 * 通过反射获得Class声明的范型Class.
 * 通过反射,获得方法输入参数第index个输入参数的所有泛型参数的实际类型. 如: public void add(Map<String, Buyer> maps, List<String> names){}
 * @param method 方法
 * @param index 第几个输入参数
 * @return 输入参数的泛型参数的实际类型集合, 如果没有实现ParameterizedType接口,即不支持泛型,所以直接返回空集合
 */
@SuppressWarnings("rawtypes")
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 RuntimeException("你输入的索引" + (index < 0 ? "不能小于0" : "超出了参数的总数"));
	}
	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;
}
 
Example 4
Source File: ClassUtils.java    From joyqueue with Apache License 2.0 6 votes vote down vote up
public static Class<?> getParameterizedType(Class<?> source, Class<?> target, int index) {
    Type[] genericInterfaces = source.getGenericInterfaces();

    if (ArrayUtils.isEmpty(genericInterfaces)) {
        return null;
    }

    for (Type genericInterface : genericInterfaces) {
        if (genericInterface instanceof ParameterizedType) {
            ParameterizedType parameterizedType = (ParameterizedType) genericInterface;

            if (parameterizedType.getRawType().getTypeName().equals(target.getName())) {
                return (Class<?>) parameterizedType.getActualTypeArguments()[index];
            }
        }
    }

    return null;
}
 
Example 5
Source File: ProviderFactory.java    From cxf with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
public <T> ContextProvider<T> createContextProvider(Type contextType,
                                                    Message m) {
    Class<?> contextCls = InjectionUtils.getActualType(contextType);
    if (contextCls == null) {
        return null;
    }
    for (ProviderInfo<ContextProvider<?>> cr : contextProviders) {
        Type[] types = cr.getProvider().getClass().getGenericInterfaces();
        for (Type t : types) {
            if (t instanceof ParameterizedType) {
                ParameterizedType pt = (ParameterizedType)t;
                Type[] args = pt.getActualTypeArguments();
                if (args.length > 0) {
                    Class<?> argCls = InjectionUtils.getActualType(args[0]);

                    if (argCls != null && argCls.isAssignableFrom(contextCls)) {
                        return (ContextProvider<T>)cr.getProvider();
                    }
                }
            }
        }
    }
    return null;
}
 
Example 6
Source File: PropertyLoader.java    From properties with Apache License 2.0 6 votes vote down vote up
/**
 * Get collection element type for given type. Given type type should
 * be assignable from {@link Collection}. For collections without
 * generic returns {@link String}.
 */
protected Class<?> getCollectionElementType(Type genericType) throws ConversionException {
    if (genericType instanceof ParameterizedType) {
        ParameterizedType parameterizedType = (ParameterizedType) genericType;
        Type[] typeArguments = parameterizedType.getActualTypeArguments();
        if (typeArguments.length != 1) {
            throw new ConversionException("Types with more then one generic are not supported");
        }

        Type type = typeArguments[0];
        if (type instanceof Class) {
            return (Class<?>) type;
        }

        throw new ConversionException(String.format("Could not resolve generic type <%s>", type));
    }
    return String.class;
}
 
Example 7
Source File: EmbedListEncoder.java    From bugu-mongo with Apache License 2.0 5 votes vote down vote up
@Override
public Object encode() {
    Object result = null;
    Class<?> type = field.getType();
    if(type.isArray()){
        Class<?> comType = type.getComponentType();
        if(comType.isEnum()){
            result = encodeEnumArray(value);
        }else{
            result = encodeArray(value);
        }
    }else{
        ParameterizedType paramType = (ParameterizedType)field.getGenericType();
        Type[] types = paramType.getActualTypeArguments();
        int len = types.length;
        if(len == 1){
            Class<?> realCls = (Class)types[0];
            if(realCls.isEnum()){
                result = encodeEnumCollection(value);
            }else{
                result = encodeCollection(value);
            }
        }else if(len == 2){
            result = encodeMap();
        }
    }
    return result;
}
 
Example 8
Source File: TypeToken.java    From RxCache with Apache License 2.0 5 votes vote down vote up
public TypeToken() {

        Type superclass = getClass().getGenericSuperclass();
        if (superclass instanceof Class) {
            throw new RxCacheException("No generics found!");
        }
        ParameterizedType type = (ParameterizedType) superclass;
        this.type = type.getActualTypeArguments()[0];
    }
 
Example 9
Source File: EmbedListEncoder.java    From bugu-mongo with Apache License 2.0 5 votes vote down vote up
private Object encodeMap(){
    //for Map<K,V>, first to check the type of V
    ParameterizedType paramType = (ParameterizedType)field.getGenericType();
    Type[] types = paramType.getActualTypeArguments();
    boolean isArray = false;
    boolean isCollection = false;
    boolean isSingle = false;
    if(types[1] instanceof GenericArrayType){
        isArray = true;
    }else if(types[1] instanceof ParameterizedType){
        isCollection = true;
    }else{
        //in JDK8, type[1] of array, is a class, not array
        Class<?> actualType = FieldUtil.getClassOfType(types[1]);
        if(actualType.isArray()){
            isArray = true;
        }else{
            isSingle = true;
        }
    }
    //encode value by different type of V
    Map map = (Map)value;
    Map result = new HashMap();
    for(Object key : map.keySet()){
        Object entryValue = map.get(key);
        if(entryValue == null){
            result.put(key, null);
            continue;
        }
        if(isSingle){
            result.put(key, MapperUtil.toDBObject(entryValue));
        }else if(isArray){
            result.put(key, encodeArray(entryValue));
        }else if(isCollection){
            result.put(key, encodeCollection(entryValue));
        }
    }
    return result;
}
 
Example 10
Source File: SerializableTypeWrapperTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void wildcardType() throws Exception {
	ParameterizedType typeSource = (ParameterizedType) SerializableTypeWrapper.forField(Fields.class.getField("wildcardType"));
	WildcardType type = (WildcardType) typeSource.getActualTypeArguments()[0];
	assertThat(type.toString(), equalTo("? extends java.lang.CharSequence"));
	assertSerialzable(type);
	assertSerialzable(type.getLowerBounds());
	assertSerialzable(type.getUpperBounds());
}
 
Example 11
Source File: PojoUtils.java    From dubbo-2.6.5 with Apache License 2.0 5 votes vote down vote up
/**
 * Get parameterized type
 *
 * @param genericType generic type
 * @param index       index of the target parameterized type
 * @return Return Person.class for List<Person>, return Person.class for Map<String, Person> when index=0
 */
private static Type getGenericClassByIndex(Type genericType, int index) {
    Type clazz = null;
    // find parameterized type
    if (genericType instanceof ParameterizedType) {
        ParameterizedType t = (ParameterizedType) genericType;
        Type[] types = t.getActualTypeArguments();
        clazz = types[index];
    }
    return clazz;
}
 
Example 12
Source File: SpecimenType.java    From jfixture with MIT License 5 votes vote down vote up
private static List<SpecimenType> resolveGenericArguments(ParameterizedType parameterizedType, SpecimenType contextualType) {
    List<SpecimenType> resolvedGenericTypes = new ArrayList<SpecimenType>();

    Type[] genericTypes = parameterizedType.getActualTypeArguments();
    for(Type genericType : genericTypes) {
        SpecimenType resolved = convertPossibleGenericTypeToSpecimenType(genericType, contextualType);
        resolvedGenericTypes.add(resolved);
    }
    return resolvedGenericTypes;
}
 
Example 13
Source File: StatefulFactory.java    From statefulj with Apache License 2.0 5 votes vote down vote up
/**
 * @param entityToRepositoryMapping
 * @param bfName
 * @param bf
 * @throws ClassNotFoundException
 */
private void mapEntityToRepository(Map<Class<?>, String> entityToRepositoryMapping,
		String bfName, BeanDefinition bf) throws ClassNotFoundException {

	// Determine the Entity Class associated with the Repo
	//
	String value = (String)bf.getPropertyValues().getPropertyValue("repositoryInterface").getValue();
	Class<?> repoInterface = Class.forName(value);
	Class<?> entityType = null;
	for(Type type : repoInterface.getGenericInterfaces()) {
		if (type instanceof ParameterizedType) {
			ParameterizedType parmType = (ParameterizedType)type;
			if (Repository.class.isAssignableFrom((Class<?>)parmType.getRawType()) &&
			    parmType.getActualTypeArguments() != null &&
			    parmType.getActualTypeArguments().length > 0) {
				entityType = (Class<?>)parmType.getActualTypeArguments()[0];
				break;
			}
		}
	}

	if (entityType == null) {
		throw new RuntimeException("Unable to determine Entity type for class " + repoInterface.getName());
	}

	// Map Entity to the RepositoryFactoryBeanSupport bean
	//
	logger.debug("Mapped \"{}\" to repo \"{}\", beanId=\"{}\"", entityType.getName(), value, bfName);

	entityToRepositoryMapping.put(entityType, bfName);
}
 
Example 14
Source File: TypeLiteral.java    From incubator-tamaya with Apache License 2.0 5 votes vote down vote up
/**
 * Checks the current implemented generic interfaces and evaluates the given single type parameter.
 *
 * @param clazz         the class to check, not  {@code null}.
 * @param interfaceType the interface type to be checked, not {@code null}.
 * @return the generic type parameters, or an empty array, if it cannot be evaluated.
 */
public static Type[] getGenericInterfaceTypeParameters(Class<?> clazz, Class<?> interfaceType) {
    Objects.requireNonNull(clazz, "Class parameter must be given.");
    Objects.requireNonNull(interfaceType, "Interface parameter must be given.");

    for (Type type : clazz.getGenericInterfaces()) {
        if (type instanceof ParameterizedType) {
            ParameterizedType parameterizedType = (ParameterizedType) type;
            if(parameterizedType.getRawType().equals(interfaceType)){
                return parameterizedType.getActualTypeArguments();
            }
        }
    }
    return EMPTY_TYPE_ARRAY;
}
 
Example 15
Source File: ApiSurface.java    From beam with Apache License 2.0 5 votes vote down vote up
/**
 * Adds any types exposed to this set. Even if the root type is to be pruned, the actual type
 * arguments are processed.
 */
private void addExposedTypes(ParameterizedType type, Class<?> cause) {
  // Even if the type is already done, this link to it may be new
  boolean alreadyDone = done(type);
  if (!pruned(type)) {
    visit(type);
    recordExposure(type, cause);
  }
  if (alreadyDone) {
    return;
  }

  // For a parameterized type, pruning does not take place
  // here, only for the raw class.
  // The type parameters themselves may not be pruned,
  // for example with List<MyApiType> probably the
  // standard List is pruned, but MyApiType is not.
  LOG.debug(
      "Adding exposed types from {}, which is the raw type on parameterized type {}",
      type.getRawType(),
      type);
  addExposedTypes(type.getRawType(), cause);
  for (Type typeArg : type.getActualTypeArguments()) {
    LOG.debug(
        "Adding exposed types from {}, which is a type argument on parameterized type {}",
        typeArg,
        type);
    addExposedTypes(typeArg, cause);
  }
}
 
Example 16
Source File: TypeMirrors.java    From FreeBuilder with Apache License 2.0 5 votes vote down vote up
/** Returns a {@link TypeMirror} for the given type. */
public static TypeMirror typeMirror(Types typeUtils, Elements elementUtils, Type type) {
  if (type instanceof Class) {
    return typeMirror(typeUtils, elementUtils, (Class<?>) type);
  } else if (type instanceof GenericArrayType) {
    Type componentType = ((GenericArrayType) type).getGenericComponentType();
    return typeUtils.getArrayType(typeMirror(typeUtils, elementUtils, componentType));
  } else if (type instanceof ParameterizedType) {
    ParameterizedType pType = (ParameterizedType) type;
    DeclaredType rawType = (DeclaredType) typeMirror(typeUtils, elementUtils, pType.getRawType());
    List<TypeMirror> typeArgumentMirrors = new ArrayList<>();
    for (Type typeArgument : pType.getActualTypeArguments()) {
      typeArgumentMirrors.add(typeMirror(typeUtils, elementUtils, typeArgument));
    }
    DeclaredType owner = (DeclaredType) typeMirror(typeUtils, elementUtils, pType.getOwnerType());
    return typeUtils.getDeclaredType(
        owner,
        (TypeElement) rawType.asElement(),
        typeArgumentMirrors.toArray(new TypeMirror[typeArgumentMirrors.size()]));
  } else if (type instanceof WildcardType) {
    Type lowerBound = getOnlyType(((WildcardType) type).getLowerBounds());
    Type upperBound = getOnlyType(((WildcardType) type).getUpperBounds());
    if (Object.class.equals(upperBound)) {
      upperBound = null;
    }
    return typeUtils.getWildcardType(
        typeMirror(typeUtils, elementUtils, upperBound),
        typeMirror(typeUtils, elementUtils, lowerBound));
  } else if (type == null) {
    return null;
  } else if (type instanceof TypeVariable) {
    throw new IllegalArgumentException("Type variables not supported");
  } else {
    throw new IllegalArgumentException("Unrecognized Type subclass " + type.getClass());
  }
}
 
Example 17
Source File: ClassUtils.java    From quarkus-http with Apache License 2.0 4 votes vote down vote up
private static Class<?> resolvePotentialTypeVariable(Type messageType, Class<?> c, Class actualClass) {
    if(messageType instanceof Class) {
        return (Class<?>) messageType;
    } else if(messageType instanceof TypeVariable) {
        Type var = messageType;
        int tvpos = 0;
        List<Class> parents = new ArrayList<>();
        Class i = actualClass;
        while (i != c) {
            parents.add(i);
            i = i.getSuperclass();
        }
        Collections.reverse(parents);
        for(Class ptype : parents) {
            Type type = ptype.getGenericSuperclass();
            if(!(type instanceof ParameterizedType)) {
                throw JsrWebSocketMessages.MESSAGES.unknownHandlerType(actualClass);
            }
            ParameterizedType pt = (ParameterizedType) type;
            if(tvpos == -1) {

                TypeVariable[] typeParameters = ((Class) pt.getRawType()).getTypeParameters();
                for(int j = 0; j <  typeParameters.length; ++j) {
                    TypeVariable tp = typeParameters[j];
                    if(tp.getName().equals(((TypeVariable)var).getName())) {
                        tvpos = j;
                        break;
                    }
                }
            }
            var = pt.getActualTypeArguments()[tvpos];
            if(var instanceof Class) {
                return (Class<?>) var;
            }
            tvpos = -1;
        }
        return (Class<?>) var;
    } else {
        throw JsrWebSocketMessages.MESSAGES.unknownHandlerType(actualClass);
    }

}
 
Example 18
Source File: AbstractCrudServiceImpl.java    From jwala with Apache License 2.0 4 votes vote down vote up
public AbstractCrudServiceImpl() {
    ParameterizedType genericSuperclass = (ParameterizedType) getClass().getGenericSuperclass();
    entityClass = (Class<T>) genericSuperclass.getActualTypeArguments()[0];
}
 
Example 19
Source File: BuguMapper.java    From bugu-mongo with Apache License 2.0 4 votes vote down vote up
private static Map fetchMapValue(Object val, Field field) {
    Map map = (Map)val;
    if(map.isEmpty()){
        return null;
    }
    
    //for Map<K,V>, first to check the type of V
    ParameterizedType paramType = (ParameterizedType)field.getGenericType();
    Type[] types = paramType.getActualTypeArguments();
    boolean isArray = false;
    boolean isCollection = false;
    boolean isSingle = false;
    Class vType = null;
    Class elementType = null;
    if(types[1] instanceof GenericArrayType){
        isArray = true;
        GenericArrayType g = (GenericArrayType)types[1];
        elementType = (Class)g.getGenericComponentType();
    }else if(types[1] instanceof ParameterizedType){
        isCollection = true;
        ParameterizedType p = (ParameterizedType)types[1];
        vType = (Class)p.getRawType();
        elementType = (Class)p.getActualTypeArguments()[0];
    }else{
        //in JDK8, type[1] of array, is a class, not array
        Class<?> actualType = FieldUtil.getClassOfType(types[1]);
        if(actualType.isArray()){
            isArray = true;
            elementType = actualType.getComponentType();
        }else{
            isSingle = true;
        }
    }
    
    //get value by different type of V
    Map result = new HashMap();
    Class<?> cls  = null;
    InternalDao dao = null;
    if(isSingle){
        cls = FieldUtil.getRealType((Class)types[1], field);
        dao = DaoCache.getInstance().get(cls);
    }
    for(Object key : map.keySet()){
        Object entryValue = map.get(key);
        if(entryValue == null){
            result.put(key, null);
            continue;
        }
        if(isSingle){
            BuguEntity refObj = (BuguEntity)entryValue;
            String id = refObj.getId();
            Object value = dao.findOne(id);
            result.put(key, value);
        }else if(isArray){
            Object arr = fetchArrayValue(entryValue, field, elementType);
            result.put(key, arr);
        }else if(isCollection){
            List list = fetchCollectionValue(entryValue, field, elementType);
            if(DataType.isListType(vType)){
                result.put(key, list);
            }
            else if(DataType.isSetType(vType)){
                result.put(key, new HashSet(list));
            }
            else if(DataType.isQueueType(vType)){
                result.put(key, new LinkedList(list));
            }
        }
    }
    return result;
}
 
Example 20
Source File: MethodTemplateProcessor.java    From ats-framework with Apache License 2.0 4 votes vote down vote up
private void configureTemplate(
                                Method actionImplementation,
                                String actionName,
                                String[] paramNames,
                                boolean registerAction,
                                String[] paramTypes,
                                String transferUnit,
                                boolean isDeprecated ) {

    try {
        placeHolderValues.put("$METHOD_NAME$",
                              toCamelNotation(actionImplementation.getDeclaringClass().getSimpleName(),
                                              actionName));
        placeHolderValues.put("$ACTION_NAME$", actionName);

        Class<?> returnType = actionImplementation.getReturnType();
        //construct the return type
        String returnTypeName = returnType.getSimpleName();
        StringBuilder execDefinition = new StringBuilder();
        if (!"void".equals(returnTypeName)) {
            execDefinition.append("return ( ");
            if (returnType.isPrimitive() && !returnType.isArray()) {
                execDefinition.append(getObjectTypeForPrimitive(returnTypeName));
            } else {

                Type genericReturnType = actionImplementation.getGenericReturnType();
                if (genericReturnType instanceof ParameterizedType) {
                    StringBuilder typeArgsString = new StringBuilder();
                    ParameterizedType type = (ParameterizedType) genericReturnType;
                    Type[] typeArguments = type.getActualTypeArguments();
                    for (Type typeArg : typeArguments) {
                        Class<?> typeArgClass = (Class<?>) typeArg;
                        typeArgsString.append(typeArgClass.getSimpleName()).append(", ");
                    }
                    if (typeArgsString.length() > 0) {
                        returnTypeName += "<" + typeArgsString.substring(0, typeArgsString.length() - 2)
                                          + ">";
                    }
                }
                execDefinition.append(returnTypeName);
            }
            execDefinition.append(" ) ");
        }
        placeHolderValues.put("$RETURN_TYPE$", returnTypeName);
        placeHolderValues.put("$EXEC_RETURN_DEFINITION$", execDefinition.toString());
        if (registerAction) {
            placeHolderValues.put("$EXECUTE_ACTION$", "executeAction");
        } else {
            placeHolderValues.put("$EXECUTE_ACTION$", "executeActionWithoutRegister");
        }

        StringBuilder paramDefinition = new StringBuilder();
        StringBuilder argumentArray = new StringBuilder();

        for (int i = 0; i < paramNames.length; i++) {
            paramDefinition.append(paramTypes[i] + " " + paramNames[i] + ", ");
            argumentArray.append(paramNames[i] + ", ");
        }
        String paramDefinitionStr = paramDefinition.toString();
        String argumentArrayStr = argumentArray.toString();

        if (paramDefinition.length() > 2) {
            paramDefinitionStr = paramDefinitionStr.substring(0, paramDefinition.length() - 2);
            argumentArrayStr = argumentArrayStr.substring(0, argumentArrayStr.length() - 2);
        }
        placeHolderValues.put("$PARAMETERS$", paramDefinitionStr);
        placeHolderValues.put("$ARGUMENTS$", argumentArrayStr);

        if (StringUtils.isNullOrEmpty(transferUnit)) {
            placeHolderValues.put("$META_KEYS$", "");
            placeHolderValues.put("$META_VALUES$", "");
        } else {
            placeHolderValues.put("$META_KEYS$", ", " + arrayToString(new String[]{ "transferUnit" }));
            placeHolderValues.put("$META_VALUES$", ", " + arrayToString(new String[]{ transferUnit }));
        }

        if (isDeprecated) {
            placeHolderValues.put("$DEPRECATED$", "    @Deprecated");
        } else {
            placeHolderValues.put("$DEPRECATED$", "");
        }
    } catch (Exception e) {
        throw new BuildException("Error building Agent action stub for action method "
                                 + actionImplementation.toString(), e);
    }
}