List of usage examples for java.lang.reflect ParameterizedType getActualTypeArguments
Type[] getActualTypeArguments();
From source file:ca.uhn.fhir.context.RuntimePrimitiveDatatypeDefinition.java
private void determineNativeType(Class<? extends IPrimitiveType<?>> theImplementingClass) { Class<?> clazz = theImplementingClass; while (clazz.equals(Object.class) == false) { Type type = clazz.getGenericSuperclass(); if (type instanceof ParameterizedType) { ParameterizedType superPt = (ParameterizedType) type; Type rawType = superPt.getRawType(); if (rawType instanceof Class) { Class<?> rawClass = (Class<?>) rawType; if (rawClass.getName().endsWith(".BasePrimitive") || rawClass.getName().endsWith(".PrimitiveType")) { Type typeVariable = superPt.getActualTypeArguments()[0]; if (typeVariable instanceof Class) { myNativeType = (Class<?>) typeVariable; break; }/* w ww . j av a 2s.c om*/ } } } clazz = clazz.getSuperclass(); } }
From source file:com.thinkbiganalytics.spark.datavalidator.functions.CleanseAndValidateRow.java
private Class resolveValidatorParamType(ValidationPolicy validator, Map<Class, Class> validatorParamType) { Class expectedParamClazz = validatorParamType.get(validator.getClass()); if (expectedParamClazz == null) { // Cache for future references Object t = validator.getClass().getGenericInterfaces()[0]; if (t instanceof ParameterizedType) { ParameterizedType type = (ParameterizedType) t; expectedParamClazz = (Class) type.getActualTypeArguments()[0]; } else {// w ww.j a v a2s .c om expectedParamClazz = String.class; } validatorParamType.put(validator.getClass(), expectedParamClazz); } return expectedParamClazz; }
From source file:org.evosuite.utils.generic.GenericUtils.java
/** * TODO: Try to match p2 superclasses? //from www. j av a 2 s .co m * * @param p1 Desired TypeVariable assignment * @param p2 Generic type with the TypeVariables that need assignment * @return */ public static Map<TypeVariable<?>, Type> getMatchingTypeParameters(ParameterizedType p1, ParameterizedType p2) { logger.debug("Matching generic types between " + p1 + " and " + p2); Map<TypeVariable<?>, Type> map = new HashMap<TypeVariable<?>, Type>(); if (!p1.getRawType().equals(p2.getRawType())) { logger.debug("Raw types do not match!"); GenericClass ownerClass = new GenericClass(p2); if (GenericClass.isSubclass(p1.getRawType(), p2.getRawType())) { logger.debug(p1 + " is a super type of " + p2); Map<TypeVariable<?>, Type> commonsMap = TypeUtils.determineTypeArguments((Class<?>) p2.getRawType(), p1); logger.debug("Adding to map: " + commonsMap); // TODO: Now we would need to iterate over the type parameters, and update the map? //map.putAll(commonsMap); for (TypeVariable<?> t : map.keySet()) { logger.debug(t + ": " + t.getGenericDeclaration()); } // For each type variable of the raw type, map the parameter type to that type Type[] p2TypesA = ((Class<?>) p2.getRawType()).getTypeParameters(); Type[] p2TypesB = p2.getActualTypeArguments(); for (int i = 0; i < p2TypesA.length; i++) { Type a = p2TypesA[i]; Type b = p2TypesB[i]; logger.debug("Should be mapping " + a + " and " + b); if (a instanceof TypeVariable<?>) { logger.debug(a + " is a type variable: " + ((TypeVariable<?>) a).getGenericDeclaration()); if (b instanceof TypeVariable<?>) { logger.debug( b + " is a type variable: " + ((TypeVariable<?>) b).getGenericDeclaration()); if (commonsMap.containsKey((TypeVariable<?>) a) && !(commonsMap.get((TypeVariable<?>) a) instanceof WildcardType) && !(commonsMap.get((TypeVariable<?>) a) instanceof TypeVariable<?>)) map.put((TypeVariable<?>) b, commonsMap.get((TypeVariable<?>) a)); //else // map.put((TypeVariable<?>)a, b); } } // if(b instanceof TypeVariable<?>) { // if(map.containsKey(a)) // map.put((TypeVariable<?>)b, map.get(a)); // //else // // map.put((TypeVariable<?>)b, a); // } logger.debug("Updated map: " + map); } } for (GenericClass interfaceClass : ownerClass.getInterfaces()) { if (interfaceClass.isParameterizedType()) map.putAll(getMatchingTypeParameters(p1, (ParameterizedType) interfaceClass.getType())); else logger.debug("Interface " + interfaceClass + " is not parameterized"); } if (ownerClass.getRawClass().getSuperclass() != null) { GenericClass ownerSuperClass = ownerClass.getSuperClass(); if (ownerSuperClass.isParameterizedType()) map.putAll(getMatchingTypeParameters(p1, (ParameterizedType) ownerSuperClass.getType())); else logger.debug("Super type " + ownerSuperClass + " is not parameterized"); } return map; } for (int i = 0; i < p1.getActualTypeArguments().length; i++) { Type t1 = p1.getActualTypeArguments()[i]; Type t2 = p2.getActualTypeArguments()[i]; if (t1 == t2) continue; logger.debug("First match: " + t1 + " - " + t2); if (t1 instanceof TypeVariable<?>) { map.put((TypeVariable<?>) t1, t2); } if (t2 instanceof TypeVariable<?>) { map.put((TypeVariable<?>) t2, t1); } else if (t2 instanceof ParameterizedType && t1 instanceof ParameterizedType) { map.putAll(getMatchingTypeParameters((ParameterizedType) t1, (ParameterizedType) t2)); } logger.debug("Updated map: " + map); } if (p1.getOwnerType() != null && p1.getOwnerType() instanceof ParameterizedType && p2.getOwnerType() instanceof ParameterizedType) { map.putAll(getMatchingTypeParameters((ParameterizedType) p1.getOwnerType(), (ParameterizedType) p2.getOwnerType())); } return map; }
From source file:org.optaplanner.core.impl.domain.solution.cloner.FieldAccessingSolutionCloner.java
private boolean isTypeArgumentDeepCloned(Type genericType) { // Check the generic type arguments of the field. // Yes, it is possible for fields and methods, but not instances! if (genericType instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType) genericType; for (Type actualTypeArgument : parameterizedType.getActualTypeArguments()) { if (actualTypeArgument instanceof Class && isClassDeepCloned((Class) actualTypeArgument)) { return true; }/*from ww w . jav a 2 s.c om*/ if (isTypeArgumentDeepCloned(actualTypeArgument)) { return true; } } } return false; }
From source file:cn.afterturn.easypoi.excel.export.base.ExportCommonService.java
/** * ??/*from w ww. ja va 2 s . co m*/ * * @param targetId ID */ public void getAllExcelField(String[] exclusions, String targetId, Field[] fields, List<ExcelExportEntity> excelParams, Class<?> pojoClass, List<Method> getMethods, ExcelEntity excelGroup) throws Exception { List<String> exclusionsList = exclusions != null ? Arrays.asList(exclusions) : null; ExcelExportEntity excelEntity; // ??filed for (int i = 0; i < fields.length; i++) { Field field = fields[i]; // ?collection,?java,? if (PoiPublicUtil.isNotUserExcelUserThis(exclusionsList, field, targetId)) { continue; } // Excel ??? if (field.getAnnotation(Excel.class) != null) { Excel excel = field.getAnnotation(Excel.class); String name = PoiPublicUtil.getValueByTargetId(excel.name(), targetId, null); if (StringUtils.isNotBlank(name)) { excelParams.add(createExcelExportEntity(field, targetId, pojoClass, getMethods, excelGroup)); } } else if (PoiPublicUtil.isCollection(field.getType())) { ExcelCollection excel = field.getAnnotation(ExcelCollection.class); ParameterizedType pt = (ParameterizedType) field.getGenericType(); Class<?> clz = (Class<?>) pt.getActualTypeArguments()[0]; List<ExcelExportEntity> list = new ArrayList<ExcelExportEntity>(); getAllExcelField(exclusions, StringUtils.isNotEmpty(excel.id()) ? excel.id() : targetId, PoiPublicUtil.getClassFields(clz), list, clz, null, null); excelEntity = new ExcelExportEntity(); excelEntity.setName(PoiPublicUtil.getValueByTargetId(excel.name(), targetId, null)); if (i18nHandler != null) { excelEntity.setName(i18nHandler.getLocaleName(excelEntity.getName())); } excelEntity.setOrderNum( Integer.valueOf(PoiPublicUtil.getValueByTargetId(excel.orderNum(), targetId, "0"))); excelEntity.setMethod(PoiReflectorUtil.fromCache(pojoClass).getGetMethod(field.getName())); excelEntity.setList(list); excelParams.add(excelEntity); } else { List<Method> newMethods = new ArrayList<Method>(); if (getMethods != null) { newMethods.addAll(getMethods); } newMethods.add(PoiReflectorUtil.fromCache(pojoClass).getGetMethod(field.getName())); ExcelEntity excel = field.getAnnotation(ExcelEntity.class); if (excel.show() && StringUtils.isEmpty(excel.name())) { throw new ExcelExportException("if use ExcelEntity ,name mus has value ,data: " + ReflectionToStringBuilder.toString(excel), ExcelExportEnum.PARAMETER_ERROR); } getAllExcelField(exclusions, StringUtils.isNotEmpty(excel.id()) ? excel.id() : targetId, PoiPublicUtil.getClassFields(field.getType()), excelParams, field.getType(), newMethods, excel.show() ? excel : null); } } }
From source file:me.ronghai.sa.dao.impl.AbstractModelDAOWithJDBCImpl.java
@SuppressWarnings("unchecked") public AbstractModelDAOWithJDBCImpl() { ParameterizedType type = (ParameterizedType) getClass().getGenericSuperclass(); this.entityClass = (Class<E>) type.getActualTypeArguments()[0]; }
From source file:info.archinnov.achilles.internal.metadata.parsing.PropertyParser.java
private <K, V> Pair<Class<K>, Class<V>> determineMapGenericTypes(Field field) { log.trace("Determine generic types for field Map<K,V> {} of entity class {}", field.getName(), field.getDeclaringClass().getCanonicalName()); Type genericType = field.getGenericType(); ParameterizedType pt = (ParameterizedType) genericType; Type[] actualTypeArguments = pt.getActualTypeArguments(); Class<K> keyClass = getClassFromType(actualTypeArguments[0]); Class<V> valueClass = getClassFromType(actualTypeArguments[1]); return Pair.create(keyClass, valueClass); }
From source file:com.github.reinert.jjschema.v1.PropertyWrapper.java
public PropertyWrapper(CustomSchemaWrapper ownerSchemaWrapper, Set<ManagedReference> managedReferences, Method method, Field field) { super(null);//from w w w .j av a 2 s .c o m if (method == null) throw new RuntimeException("Error at " + ownerSchemaWrapper.getJavaType().getName() + ": Cannot instantiate a PropertyWrapper with a null method."); this.ownerSchemaWrapper = ownerSchemaWrapper; this.field = field; this.method = method; String relativeId; Class<?> propertyType = method.getReturnType(); Class<?> collectionType = null; final String propertiesStr = "/properties/"; String itemsStr = "/items"; if (Collection.class.isAssignableFrom(propertyType)) { collectionType = method.getReturnType(); ParameterizedType genericType = (ParameterizedType) method.getGenericReturnType(); propertyType = (Class<?>) genericType.getActualTypeArguments()[0]; relativeId = propertiesStr + getName() + itemsStr; } else { relativeId = propertiesStr + getName(); } processReference(propertyType); if (getAccessibleObject().getAnnotation(SchemaIgnore.class) != null) { this.schemaWrapper = new EmptySchemaWrapper(); } else if (getReferenceType() == ReferenceType.BACKWARD) { SchemaWrapper schemaWrapperLocal; String id = processId(method.getReturnType()); if (id != null) { schemaWrapperLocal = new RefSchemaWrapper(propertyType, id); ownerSchemaWrapper.pushReference(getManagedReference()); } else { if (ownerSchemaWrapper.pushReference(getManagedReference())) { String relativeId1 = ownerSchemaWrapper.getRelativeId(); if (relativeId1.endsWith(itemsStr)) { relativeId1 = relativeId1.substring(0, relativeId1.substring(0, relativeId1.length() - itemsStr.length()).lastIndexOf("/") - (propertiesStr.length() - 1)); } else { relativeId1 = relativeId1.substring(0, relativeId1.lastIndexOf("/") - (propertiesStr.length() - 1)); } schemaWrapperLocal = new RefSchemaWrapper(propertyType, relativeId1); } else schemaWrapperLocal = new EmptySchemaWrapper(); } if (schemaWrapperLocal.isRefWrapper() && collectionType != null) this.schemaWrapper = SchemaWrapperFactory .createArrayRefWrapper((RefSchemaWrapper) schemaWrapperLocal); else this.schemaWrapper = schemaWrapperLocal; } else if (ownerSchemaWrapper.getJavaType() == propertyType) { SchemaWrapper schemaWrapperLocal = new RefSchemaWrapper(propertyType, ownerSchemaWrapper.getRelativeId()); if (collectionType != null) { this.schemaWrapper = SchemaWrapperFactory .createArrayRefWrapper((RefSchemaWrapper) schemaWrapperLocal); } else { this.schemaWrapper = schemaWrapperLocal; } } else { if (getReferenceType() == ReferenceType.FORWARD) { ownerSchemaWrapper.pullReference(getManagedReference()); } String relativeId1 = ownerSchemaWrapper.getRelativeId() + relativeId; if (collectionType != null) { this.schemaWrapper = SchemaWrapperFactory.createArrayWrapper(collectionType, propertyType, managedReferences, relativeId1); } else { this.schemaWrapper = SchemaWrapperFactory.createWrapper(propertyType, managedReferences, relativeId1); } processAttributes(getNode(), getAccessibleObject()); processNullable(); } }
From source file:org.guiceyfruit.spring.support.AutowiredMemberProvider.java
protected Map provideMapValues(Map map, Member member, TypeLiteral<?> type, Predicate<Binding> filter) { Type typeInstance = type.getType(); if (typeInstance instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType) typeInstance; Type[] arguments = parameterizedType.getActualTypeArguments(); if (arguments.length == 2) { Type key = arguments[0]; if (key instanceof Class) { Class<?> keyType = (Class<?>) key; if (keyType != Object.class && keyType != String.class) { throw new ProvisionException("Cannot inject Map instances with a key type of " + keyType.getName() + " for " + member); }/*from w ww .j av a 2s .com*/ Type valueType = arguments[1]; if (valueType instanceof Class) { Class<?> componentType = (Class<?>) valueType; if (componentType != Object.class) { Set<Binding<?>> set = getSortedBindings(componentType, filter); if (set.isEmpty()) { // TODO return null or empty collection if nothing to inject? return null; } for (Binding<?> binding : set) { Object keyValue = binding.getKey().toString(); Object value = binding.getProvider().get(); map.put(keyValue, value); } return map; } } } } } // TODO return null or empty collection if nothing to inject? return null; }
From source file:com.basistech.rosette.apimodel.ModelTest.java
private Object createObjectForType(Class<?> type, Type genericParameterType) throws IllegalAccessException, InstantiationException, InvocationTargetException { Object o = null;//from ww w .j a v a 2 s . c o m Class firstComponentType = type.isArray() ? type.getComponentType() : type; String typeName = firstComponentType.getSimpleName(); Class parameterArgClass = null; Type[] parameterArgTypes = null; if (genericParameterType != null) { if (genericParameterType instanceof ParameterizedType) { ParameterizedType aType = (ParameterizedType) genericParameterType; parameterArgTypes = aType.getActualTypeArguments(); for (Type parameterArgType : parameterArgTypes) { if (parameterArgType instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType) parameterArgType; if (isListString(parameterizedType)) { List<List<String>> rv = Lists.newArrayList(); rv.add(Lists.newArrayList("string")); return rv; } } else { parameterArgClass = (Class) parameterArgType; if ("Map".equals(typeName)) { break; } } } } } if (firstComponentType.isEnum()) { return firstComponentType.getEnumConstants()[0]; } switch (typeName) { case "byte": { if (type.isArray()) { o = "somebytes".getBytes(); } else { o = (byte) '8'; } break; } case "String": case "CharSequence": { o = "foo"; break; } case "long": case "Long": { o = (long) 123456789; break; } case "Double": case "double": { o = 1.0; break; } case "int": case "Integer": { o = 98761234; break; } case "boolean": case "Boolean": { o = false; break; } case "Collection": case "List": { if (parameterArgClass != null) { Object o1 = createObjectForType(parameterArgClass, null); List<Object> list = new ArrayList<>(); list.add(o1); o = list; } break; } case "Object": if (inputStreams) { o = new ByteArrayInputStream(new byte[0]); } else { o = "foo"; } break; case "EnumSet": break; case "Set": { if (parameterArgClass != null) { Object o1 = createObjectForType(parameterArgClass, null); Set<Object> set = new HashSet<>(); set.add(o1); o = set; } break; } case "Map": { if (parameterArgTypes != null && parameterArgTypes.length == 2) { Class keyClass = (Class) parameterArgTypes[0]; Object keyObject = createObject(keyClass); if (keyObject != null) { HashMap<Object, Object> map = new HashMap<>(); map.put(keyObject, null); o = map; } } break; } default: if (parameterArgClass != null) { Constructor[] ctors = parameterArgClass.getDeclaredConstructors(); o = createObject(ctors[0]); } else { Constructor[] ctors = firstComponentType.getDeclaredConstructors(); o = createObject(ctors[0]); } } return o; }