List of usage examples for java.lang.reflect ParameterizedType getActualTypeArguments
Type[] getActualTypeArguments();
From source file:com.evolveum.midpoint.prism.marshaller.PrismBeanInspector.java
@NotNull Type getTypeArgument(Type origType, String desc) { if (!(origType instanceof ParameterizedType)) { throw new IllegalArgumentException("Not a parametrized type " + desc); }//from w ww.ja v a 2 s. com ParameterizedType parametrizedType = (ParameterizedType) origType; Type[] actualTypeArguments = parametrizedType.getActualTypeArguments(); if (actualTypeArguments == null || actualTypeArguments.length == 0) { throw new IllegalArgumentException("No type arguments for getter " + desc); } if (actualTypeArguments.length > 1) { throw new IllegalArgumentException("Too many type arguments for getter for " + desc); } return actualTypeArguments[0]; }
From source file:com.vmware.photon.controller.swagger.resources.SwaggerJsonListing.java
/** * Converts a model property to a SwaggerModelProperty in the event that it is a collection type. * * @param property The model property to convert. * @param models The hashmap of models that are being documented so that they can be referenced by swagger-ui. * @param modelProperty The SwaggerModelProperty to convert this property into. * @return The converted SwaggerModelProperty. *//*from www .j a va 2s . c o m*/ private SwaggerModelProperty handleCollectionType(Field property, HashMap<String, SwaggerModel> models, SwaggerModelProperty modelProperty) { String type = property.getType().getSimpleName(); if (COLLECTION_TYPES.contains(type)) { ParameterizedType parameterizedType = (ParameterizedType) property.getGenericType(); Type[] genericTypes = parameterizedType.getActualTypeArguments(); if (genericTypes.length > 0) { // Swagger UI doesn't support the fact that a Parameter could be a collection/generic that // references two classes, such as HashMap<Class1, Class2>. If it did, then we wouldn't limit this method to // just COLLECTION_TYPES. Class genericClass = (Class) genericTypes[0]; addModel(models, genericClass); HashMap<String, String> items = new HashMap<>(); if (PRIMITIVE_TYPES.contains(genericClass.getSimpleName())) { items.put("type", genericClass.getSimpleName()); } else { items.put(REFERENCE_TYPE, genericClass.getSimpleName()); } modelProperty.setItems(items); } } return modelProperty; }
From source file:com.expedia.tesla.compiler.plugins.JavaTypeMapper.java
private Type fromJava(Schema.SchemaBuilder schemaBuilder, java.lang.reflect.Type jt) throws TeslaSchemaException { if (jt instanceof java.lang.Class) { return fromJavaForward(schemaBuilder, (java.lang.Class<?>) jt); } else if (jt instanceof java.lang.reflect.WildcardType) { // ? extends Interface java.lang.reflect.WildcardType wt = (java.lang.reflect.WildcardType) jt; return fromJava(schemaBuilder, wt.getUpperBounds()[0]); } else if (jt instanceof java.lang.reflect.GenericArrayType) { // T[]//from w w w .ja va2 s.c om java.lang.reflect.GenericArrayType ga = (java.lang.reflect.GenericArrayType) jt; Type elementType = fromJava(schemaBuilder, ga.getGenericComponentType()); return schemaBuilder.addType(String.format("array<%s>", elementType.getTypeId())); } else if (jt instanceof TypeVariable) { // T TypeVariable<?> tv = (TypeVariable<?>) jt; return fromJava(schemaBuilder, tv.getBounds()[0]); } else if (jt instanceof ParameterizedType) { ParameterizedType pt = (ParameterizedType) jt; java.lang.Class<?> rt = (java.lang.Class<?>) pt.getRawType(); if (java.util.Map.class.isAssignableFrom(rt)) { // Map java.lang.reflect.Type kt = (java.lang.reflect.Type) pt.getActualTypeArguments()[0]; java.lang.reflect.Type vt = (java.lang.reflect.Type) pt.getActualTypeArguments()[1]; Type keyType = fromJava(schemaBuilder, kt); Type valueType = fromJava(schemaBuilder, vt); String fs = null; java.lang.Class<?> rawType = (java.lang.Class<?>) pt.getRawType(); if (rawType.isInterface()) { fs = "map<%s,%s>"; } else { fs = "map[" + rawType.getCanonicalName() + "]<%s,%s>"; } String tid = String.format(fs, keyType.getTypeId(), valueType.getTypeId()); return schemaBuilder.addType(tid); } else if (java.util.Collection.class.isAssignableFrom(rt)) { // Collection array (List<?>, Set<?>), use Collection and // ArrayList by default java.lang.reflect.Type et = (java.lang.reflect.Type) pt.getActualTypeArguments()[0]; Type elementType = fromJava(schemaBuilder, et); String fs = null; java.lang.Class<?> rawType = (java.lang.Class<?>) pt.getRawType(); if (rawType.isInterface()) { fs = "array[java.util.Collection,java.util.ArrayList]<%s>"; if (java.util.List.class.isAssignableFrom(rt)) { fs = "array[java.util.List,java.util.ArrayList]<%s>"; } else if (java.util.Set.class.isAssignableFrom(rt)) { fs = "array[java.util.Set,java.util.HashSet]<%s>"; } } else { fs = "array[" + rawType.getCanonicalName() + "]<%s>"; } String tid = String.format(fs, elementType.getTypeId()); return schemaBuilder.addType(tid); } return fromJavaForward(schemaBuilder, rt); } else { throw new TeslaSchemaException("BUG"); } }
From source file:org.raml.emitter.RamlEmitterV2.java
/** * <p>dumpSequenceField.</p> * * @param dump a {@link java.lang.StringBuilder} object. * @param depth a int./*from w w w .ja v a2 s. c om*/ * @param field a {@link java.lang.reflect.Field} object. * @param pojo a {@link java.lang.Object} object. */ @SuppressWarnings("rawtypes") public void dumpSequenceField(StringBuilder dump, int depth, Field field, Object pojo) { if (!List.class.isAssignableFrom(field.getType())) { throw new RuntimeException("Only List can be sequence."); } currentField = field; List seq = (List) getFieldValue(field, pojo); if (seq == null || seq.size() == 0) { return; } Type type = field.getGenericType(); if (type instanceof ParameterizedType) { ParameterizedType pType = (ParameterizedType) type; Type itemType = pType.getActualTypeArguments()[0]; dump.append(indent(depth)).append(alias(field)).append(YAML_MAP_SEP); dumpSequenceItems(dump, depth, seq, itemType, false); } }
From source file:com.github.reinert.jjschema.JsonSchemaGenerator.java
protected <T> ObjectNode generatePropertySchema(Class<T> type, Method method, Field field) throws TypeException { Class<?> returnType = method != null ? method.getReturnType() : field.getType(); AccessibleObject propertyReflection = field != null ? field : method; SchemaIgnore ignoreAnn = propertyReflection.getAnnotation(SchemaIgnore.class); if (ignoreAnn != null) return null; ObjectNode schema = createInstance(); JsonManagedReference refAnn = propertyReflection.getAnnotation(JsonManagedReference.class); if (refAnn != null) { ManagedReference fowardReference; Class<?> genericClass; Class<?> collectionClass; if (Collection.class.isAssignableFrom(returnType)) { if (method != null) { ParameterizedType genericType = (ParameterizedType) method.getGenericReturnType(); genericClass = (Class<?>) genericType.getActualTypeArguments()[0]; } else { genericClass = field.getClass(); }//from www .j av a 2 s . c om collectionClass = returnType; } else { genericClass = returnType; } fowardReference = new ManagedReference(type, refAnn.value(), genericClass); if (!isFowardReferencePiled(fowardReference)) { pushFowardReference(fowardReference); } else // if (isBackwardReferencePiled(fowardReference)) { boolean a = pullFowardReference(fowardReference); boolean b = pullBackwardReference(fowardReference); //return null; return createRefSchema("#"); } } JsonBackReference backRefAnn = propertyReflection.getAnnotation(JsonBackReference.class); if (backRefAnn != null) { ManagedReference backReference; Class<?> genericClass; Class<?> collectionClass; if (Collection.class.isAssignableFrom(returnType)) { ParameterizedType genericType = (ParameterizedType) method.getGenericReturnType(); genericClass = (Class<?>) genericType.getActualTypeArguments()[0]; collectionClass = returnType; } else { genericClass = returnType; } backReference = new ManagedReference(genericClass, backRefAnn.value(), type); if (isFowardReferencePiled(backReference) && !isBackwardReferencePiled(backReference)) { pushBackwardReference(backReference); } else { // pullFowardReference(backReference); // pullBackwardReference(backReference); return null; } } if (Collection.class.isAssignableFrom(returnType)) { processPropertyCollection(method, field, schema); } else { schema = generateSchema(returnType); } // Check the field annotations, if the get method references a field, or the // method annotations on the other hand, and processSchemaProperty them to // the JsonSchema object Attributes attrs = propertyReflection.getAnnotation(Attributes.class); if (attrs != null) { processSchemaProperty(schema, attrs); // The declaration of $schema is only necessary at the root object schema.remove("$schema"); } // Check if the Nullable annotation is present, and if so, add 'null' to type attr Nullable nullable = propertyReflection.getAnnotation(Nullable.class); if (nullable != null) { if (returnType.isEnum()) { ((ArrayNode) schema.get("enum")).add("null"); } else { String oldType = schema.get(TAG_TYPE).asText(); ArrayNode typeArray = schema.putArray(TAG_TYPE); typeArray.add(oldType); typeArray.add("null"); } } return schema; }
From source file:org.fusesource.ide.generator.Generator.java
private Class<?> elementTypeClass(Type retType) { if (retType != null && retType instanceof ParameterizedType) { ParameterizedType paramType = (ParameterizedType) retType; Type[] arguments = paramType.getActualTypeArguments(); if (arguments != null && arguments.length > 0) { if (arguments[0] instanceof Class) { return (Class<?>) arguments[0]; } else { return null; }//from w w w. ja v a 2 s . com } } return null; }
From source file:org.sparkcommerce.openadmin.server.dao.provider.metadata.CollectionFieldMetadataProvider.java
protected void buildCollectionMetadata(Class<?> parentClass, Class<?> targetClass, Map<String, FieldMetadata> attributes, FieldInfo field, FieldMetadataOverride collectionMetadata, String prefix) {// w w w . j a v a 2s .c o m BasicCollectionMetadata serverMetadata = (BasicCollectionMetadata) attributes.get(field.getName()); Class<?> resolvedClass = parentClass == null ? targetClass : parentClass; BasicCollectionMetadata metadata; if (serverMetadata != null) { metadata = serverMetadata; } else { metadata = new BasicCollectionMetadata(); } metadata.setTargetClass(targetClass.getName()); metadata.setFieldName(field.getName()); if (collectionMetadata.getReadOnly() != null) { metadata.setMutable(!collectionMetadata.getReadOnly()); } if (collectionMetadata.getAddMethodType() != null) { metadata.setAddMethodType(collectionMetadata.getAddMethodType()); } if (collectionMetadata.getShowIfProperty() != null) { metadata.setShowIfProperty(collectionMetadata.getShowIfProperty()); } org.sparkcommerce.openadmin.dto.OperationTypes dtoOperationTypes = new org.sparkcommerce.openadmin.dto.OperationTypes( OperationType.BASIC, OperationType.BASIC, OperationType.BASIC, OperationType.BASIC, OperationType.BASIC); if (collectionMetadata.getAddType() != null) { dtoOperationTypes.setAddType(collectionMetadata.getAddType()); } if (collectionMetadata.getRemoveType() != null) { dtoOperationTypes.setRemoveType(collectionMetadata.getRemoveType()); } if (collectionMetadata.getFetchType() != null) { dtoOperationTypes.setFetchType(collectionMetadata.getFetchType()); } if (collectionMetadata.getInspectType() != null) { dtoOperationTypes.setInspectType(collectionMetadata.getInspectType()); } if (collectionMetadata.getUpdateType() != null) { dtoOperationTypes.setUpdateType(collectionMetadata.getUpdateType()); } if (AddMethodType.LOOKUP == metadata.getAddMethodType()) { dtoOperationTypes.setRemoveType(OperationType.NONDESTRUCTIVEREMOVE); } //don't allow additional non-persistent properties or additional foreign keys for an advanced collection datasource - they don't make sense in this context PersistencePerspective persistencePerspective; if (serverMetadata != null) { persistencePerspective = metadata.getPersistencePerspective(); persistencePerspective.setOperationTypes(dtoOperationTypes); } else { persistencePerspective = new PersistencePerspective(dtoOperationTypes, new String[] {}, new ForeignKey[] {}); metadata.setPersistencePerspective(persistencePerspective); } String foreignKeyName = null; if (serverMetadata != null) { foreignKeyName = ((ForeignKey) serverMetadata.getPersistencePerspective() .getPersistencePerspectiveItems().get(PersistencePerspectiveItemType.FOREIGNKEY)) .getManyToField(); } if (!StringUtils.isEmpty(collectionMetadata.getManyToField())) { foreignKeyName = collectionMetadata.getManyToField(); } if (foreignKeyName == null && !StringUtils.isEmpty(field.getOneToManyMappedBy())) { foreignKeyName = field.getOneToManyMappedBy(); } if (foreignKeyName == null && !StringUtils.isEmpty(field.getManyToManyMappedBy())) { foreignKeyName = field.getManyToManyMappedBy(); } if (StringUtils.isEmpty(foreignKeyName)) { throw new IllegalArgumentException( "Unable to infer a ManyToOne field name for the @AdminPresentationCollection annotated field(" + field.getName() + "). If not using the mappedBy property of @OneToMany or @ManyToMany, please make sure to explicitly define the manyToField property"); } if (serverMetadata != null) { ForeignKey foreignKey = (ForeignKey) metadata.getPersistencePerspective() .getPersistencePerspectiveItems().get(PersistencePerspectiveItemType.FOREIGNKEY); foreignKey.setManyToField(foreignKeyName); foreignKey.setForeignKeyClass(resolvedClass.getName()); foreignKey.setMutable(metadata.isMutable()); foreignKey.setOriginatingField(prefix + field.getName()); } else { ForeignKey foreignKey = new ForeignKey(foreignKeyName, resolvedClass.getName(), null, ForeignKeyRestrictionType.ID_EQ); persistencePerspective.addPersistencePerspectiveItem(PersistencePerspectiveItemType.FOREIGNKEY, foreignKey); foreignKey.setMutable(metadata.isMutable()); foreignKey.setOriginatingField(prefix + field.getName()); } String ceiling = null; checkCeiling: { if (field.getGenericType() instanceof ParameterizedType) { try { ParameterizedType pt = (ParameterizedType) field.getGenericType(); java.lang.reflect.Type collectionType = pt.getActualTypeArguments()[0]; String ceilingEntityName = ((Class<?>) collectionType).getName(); ceiling = entityConfiguration.lookupEntityClass(ceilingEntityName).getName(); break checkCeiling; } catch (NoSuchBeanDefinitionException e) { // We weren't successful at looking at entity configuration to find the type of this collection. // We will continue and attempt to find it via the Hibernate annotations } } if (!StringUtils.isEmpty(field.getOneToManyTargetEntity()) && !void.class.getName().equals(field.getOneToManyTargetEntity())) { ceiling = field.getOneToManyTargetEntity(); break checkCeiling; } if (!StringUtils.isEmpty(field.getManyToManyTargetEntity()) && !void.class.getName().equals(field.getManyToManyTargetEntity())) { ceiling = field.getManyToManyTargetEntity(); break checkCeiling; } } if (!StringUtils.isEmpty(ceiling)) { metadata.setCollectionCeilingEntity(ceiling); } if (collectionMetadata.getExcluded() != null) { if (LOG.isDebugEnabled()) { if (collectionMetadata.getExcluded()) { LOG.debug("buildCollectionMetadata:Excluding " + field.getName() + " because it was explicitly declared in config"); } else { LOG.debug("buildCollectionMetadata:Showing " + field.getName() + " because it was explicitly declared in config"); } } metadata.setExcluded(collectionMetadata.getExcluded()); } if (collectionMetadata.getFriendlyName() != null) { metadata.setFriendlyName(collectionMetadata.getFriendlyName()); } if (collectionMetadata.getSecurityLevel() != null) { metadata.setSecurityLevel(collectionMetadata.getSecurityLevel()); } if (collectionMetadata.getOrder() != null) { metadata.setOrder(collectionMetadata.getOrder()); } if (collectionMetadata.getTab() != null) { metadata.setTab(collectionMetadata.getTab()); } if (collectionMetadata.getTabOrder() != null) { metadata.setTabOrder(collectionMetadata.getTabOrder()); } if (collectionMetadata.getCustomCriteria() != null) { metadata.setCustomCriteria(collectionMetadata.getCustomCriteria()); } if (collectionMetadata.getUseServerSideInspectionCache() != null) { persistencePerspective .setUseServerSideInspectionCache(collectionMetadata.getUseServerSideInspectionCache()); } if (collectionMetadata.getCurrencyCodeField() != null) { metadata.setCurrencyCodeField(collectionMetadata.getCurrencyCodeField()); } attributes.put(field.getName(), metadata); }
From source file:org.raml.emitter.RamlEmitterV2.java
/** * <p>dumpMappingField.</p>/*from w w w . j a va 2s. co m*/ * * @param dump a {@link java.lang.StringBuilder} object. * @param depth a int. * @param field a {@link java.lang.reflect.Field} object. * @param implicit a boolean. * @param pojo a {@link java.lang.Object} object. * @param inlineLists a boolean. */ @SuppressWarnings({ "rawtypes", "unchecked" }) protected void dumpMappingField(StringBuilder dump, int depth, Field field, boolean implicit, Object pojo, boolean inlineLists) { if (!Map.class.isAssignableFrom(field.getType())) { throw new RuntimeException("invalid type"); } Map value = (Map) getFieldValue(field, pojo); MapFilter annotation = field.getAnnotation(MapFilter.class); if (annotation != null) { try { IFilter newInstance = annotation.value().newInstance(); LinkedHashMap q = new LinkedHashMap(); for (Object a : value.keySet()) { Object object = value.get(a); if (newInstance.accept(object)) { q.put(a, object); } } value = q; } catch (Exception e) { throw new RuntimeException(e); } } if (value == null || value.isEmpty()) { return; } boolean isSettings = false; if (field.getName().equals("settings")) { isSettings = true; } if (!implicit) { dump.append(indent(depth)).append(alias(field)).append(YAML_MAP_SEP).append("\n"); depth++; } ParameterizedType pType = (ParameterizedType) field.getGenericType(); Type valueType = pType.getActualTypeArguments()[1]; dumpMap(dump, depth, valueType, value, isSettings, false); }
From source file:hudson.model.Descriptor.java
/** * Infers the type of the corresponding {@link Describable} from the outer class. * This version works when you follow the common convention, where a descriptor * is written as the static nested class of the describable class. * /*from w w w .j a va2 s. c o m*/ * @since 1.278 */ protected Descriptor() { this.clazz = (Class<T>) getClass().getEnclosingClass(); if (clazz == null) throw new AssertionError(getClass() + " doesn't have an outer class. Use the constructor that takes the Class object explicitly."); // detect an type error Type bt = Types.getBaseClass(getClass(), Descriptor.class); if (bt instanceof ParameterizedType) { ParameterizedType pt = (ParameterizedType) bt; // this 't' is the closest approximation of T of Descriptor<T>. Class t = Types.erasure(pt.getActualTypeArguments()[0]); if (!t.isAssignableFrom(clazz)) throw new AssertionError("Outer class " + clazz + " of " + getClass() + " is not assignable to " + t + ". Perhaps wrong outer class?"); } // detect a type error. this Descriptor is supposed to be returned from getDescriptor(), so make sure its type match up. // this prevents a bug like http://www.nabble.com/Creating-a-new-parameter-Type-%3A-Masked-Parameter-td24786554.html try { Method getd = clazz.getMethod("getDescriptor"); if (!getd.getReturnType().isAssignableFrom(getClass())) { throw new AssertionError(getClass() + " must be assignable to " + getd.getReturnType()); } } catch (NoSuchMethodException e) { throw new AssertionError(getClass() + " is missing getDescriptor method."); } }
From source file:com.snaplogic.snaps.firstdata.Create.java
private Object prepareListObj(Object requestObj, String claszPath, String method2Invoke, Object inputData) { if (inputData != null) { Class<?> clasz = getClassType(claszPath); Method method;//from w w w . j a va2 s . c om try { method = clasz.getDeclaredMethod(String.format(GETTER, method2Invoke)); ParameterizedType fieldGenericType = (ParameterizedType) method.getGenericReturnType(); Class<?> fieldTypeParameterType = (Class<?>) fieldGenericType.getActualTypeArguments()[0]; List<Object> list = (List<Object>) method.invoke(requestObj); if (inputData instanceof List) { List<Map<String, Object>> inputList = List.class.cast(inputData); for (Map<String, Object> mapObj : inputList) { Object obj = getObject(fieldTypeParameterType.getName(), mapObj); list.add(obj); } } else if (inputData instanceof Map) { Object obj = getObject(fieldTypeParameterType.getName(), Map.class.cast(inputData)); list.add(obj); } } catch (NoSuchMethodException | SecurityException e) { log.warn(e.getMessage(), e); } catch (IllegalAccessException e) { log.warn(e.getMessage(), e); } catch (IllegalArgumentException e) { log.warn(e.getMessage(), e); } catch (InvocationTargetException e) { log.warn(e.getMessage(), e); } } return requestObj; }