List of usage examples for java.lang.reflect ParameterizedType getActualTypeArguments
Type[] getActualTypeArguments();
From source file:org.protorabbit.json.DefaultSerializer.java
@SuppressWarnings("unchecked") void invokeMethod(Method[] methods, String key, String name, JSONObject jo, Object targetObject) { Object param = null;// w ww . j a v a 2 s . c om Throwable ex = null; for (int i = 0; i < methods.length; i++) { Method m = methods[i]; if (m.getName().equals(name)) { Class<?>[] paramTypes = m.getParameterTypes(); if (paramTypes.length == 1 && jo.has(key)) { Class<?> tparam = paramTypes[0]; boolean allowNull = false; try { if (jo.isNull(key)) { // do nothing because param is already null : lets us not null on other types } else if (Long.class.isAssignableFrom(tparam) || tparam == long.class) { param = new Long(jo.getLong(key)); } else if (Double.class.isAssignableFrom(tparam) || tparam == double.class) { param = new Double(jo.getDouble(key)); } else if (Integer.class.isAssignableFrom(tparam) || tparam == int.class) { param = new Integer(jo.getInt(key)); } else if (String.class.isAssignableFrom(tparam)) { param = jo.getString(key); } else if (Enum.class.isAssignableFrom(tparam)) { param = Enum.valueOf((Class<? extends Enum>) tparam, jo.getString(key)); } else if (Boolean.class.isAssignableFrom(tparam)) { param = new Boolean(jo.getBoolean(key)); } else if (jo.isNull(key)) { param = null; allowNull = true; } else if (Collection.class.isAssignableFrom(tparam)) { if (m.getGenericParameterTypes().length > 0) { Type t = m.getGenericParameterTypes()[0]; if (t instanceof ParameterizedType) { ParameterizedType tv = (ParameterizedType) t; if (tv.getActualTypeArguments().length > 0 && tv.getActualTypeArguments()[0] == String.class) { List<String> ls = new ArrayList<String>(); JSONArray ja = jo.optJSONArray(key); if (ja != null) { for (int j = 0; j < ja.length(); j++) { ls.add(ja.getString(j)); } } param = ls; } else if (tv.getActualTypeArguments().length == 1) { ParameterizedType type = (ParameterizedType) tv.getActualTypeArguments()[0]; Class itemClass = (Class) type.getRawType(); if (itemClass == Map.class && type.getActualTypeArguments().length == 2 && type.getActualTypeArguments()[0] == String.class && type.getActualTypeArguments()[1] == Object.class) { List<Map<String, Object>> ls = new ArrayList<Map<String, Object>>(); JSONArray ja = jo.optJSONArray(key); if (ja != null) { for (int j = 0; j < ja.length(); j++) { Map<String, Object> map = new HashMap<String, Object>(); JSONObject mo = ja.getJSONObject(j); Iterator<String> keys = mo.keys(); while (keys.hasNext()) { String okey = keys.next(); Object ovalue = null; // make sure we don't get JSONObject$Null if (!mo.isNull(okey)) { ovalue = mo.get(okey); } map.put(okey, ovalue); } ls.add(map); } } param = ls; } else { getLogger().warning( "Don't know how to handle Collection of type : " + itemClass); } } else { getLogger().warning("Don't know how to handle Collection of type : " + tv.getActualTypeArguments()[0]); } } } } else { getLogger().warning( "Unable to serialize " + key + " : Don't know how to handle " + tparam); } } catch (JSONException e) { e.printStackTrace(); } if (param != null || allowNull) { try { if (m != null) { Object[] args = { param }; m.invoke(targetObject, args); ex = null; break; } } catch (SecurityException e) { ex = e; } catch (IllegalArgumentException e) { ex = e; } catch (IllegalAccessException e) { ex = e; } catch (InvocationTargetException e) { ex = e; } } } } } if (ex != null) { if (ex instanceof RuntimeException) { throw (RuntimeException) ex; } else { throw new RuntimeException(ex); } } }
From source file:com.astamuse.asta4d.data.DefaultDataTypeTransformer.java
private Pair<Class, Class> extractConvertorTypeInfo(DataValueConvertor convertor) { Type[] intfs = convertor.getClass().getGenericInterfaces(); Class rawCls;//from w w w. j ava2 s.c o m for (Type intf : intfs) { if (intf instanceof ParameterizedType) { ParameterizedType pt = (ParameterizedType) intf; rawCls = (Class) pt.getRawType(); if (rawCls.getName().equals(DataValueConvertor.class.getName()) || rawCls.getName().equals(DataValueConvertorTargetTypeConvertable.class.getName())) { Type[] typeArgs = pt.getActualTypeArguments(); return Pair.of((Class) typeArgs[0], (Class) typeArgs[1]); } } } logger.warn("Could not extract type information from DataTypeConvertor:" + convertor.getClass().getName()); return null; }
From source file:at.alladin.rmbt.shared.hstoreparser.HstoreParser.java
/** * //from ww w . j a v a 2 s. c o m * @param hstore * @return * @throws HstoreParseException */ @SuppressWarnings({ "unchecked", "rawtypes" }) public T fromJson(JSONObject json) throws HstoreParseException { T object; try { object = constructor.newInstance(); } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { throw new HstoreParseException(HstoreParseException.HSTORE_PARSE_EXCEPTION + e.getLocalizedMessage(), e); } if (object == null) { throw new HstoreParseException( HstoreParseException.HSTORE_COULD_NOT_INSTANTIATE + clazz.getCanonicalName()); } //iterate through all json entries: Iterator<String> jsonKeys = json.keys(); while (jsonKeys.hasNext()) { String key = jsonKeys.next(); //if fieldsWithKeys contain a key (=it was annotated with @HstoreKey) then try to set the value of the field in T object if (fieldsWithKeys.containsKey(key)) { final Field field = fieldsWithKeys.get(key); try { Object value = getFromJsonByField(json, key, field); field.setAccessible(true); //cast / new instance needed? if (field.isAnnotationPresent(HstoreCollection.class)) { Class<?> fieldClazz = field.getType(); //System.out.println("FieldClazz: " + fieldClazz + " -> " + fieldClazz.isAssignableFrom(Collection.class)); if (Collection.class.isAssignableFrom(fieldClazz)) { //get collection and instantiate if necessary Collection collection = (Collection) field.get(object); if (collection == null) { collection = (Collection) fieldClazz.newInstance(); } ParameterizedType fieldType = (ParameterizedType) field.getGenericType(); Class<?> genericClazz = (Class<?>) fieldType.getActualTypeArguments()[0]; //System.out.println("genericClazz: " + genericClazz); //Object jsonObject = hstore.toJson((String) value, genericClazz); Object jsonObject = null; //System.out.println(value); if (!value.equals(JSONObject.NULL)) { if (value instanceof JSONArray || value instanceof JSONObject) { jsonObject = hstore.toJson(value.toString(), genericClazz); } else { jsonObject = hstore.toJson((String) value, genericClazz); } } else { jsonObject = hstore.toJson(null, genericClazz); } if (jsonObject != null) { if (jsonObject instanceof JSONArray) { //System.out.println(jsonObject); Object[] array = hstore.fromJSONArray((JSONArray) jsonObject, genericClazz); for (int i = 0; i < array.length; i++) { //System.out.println("Created element: " + array[i]); collection.add(array[i]); } } else { Object element = hstore.fromString((String) value, genericClazz); //System.out.println("Created element: " + element); collection.add(element); } } value = collection; } else { throw new HstoreParseException(HstoreParseException.HSTORE_MUST_BE_A_COLLECTION + field + " - " + clazz.getCanonicalName()); } } if (field.isAnnotationPresent(HstoreCast.class)) { HstoreCast castDef = field.getAnnotation(HstoreCast.class); if (castDef.simpleCast()) { //simple cast field.set(object, castDef.clazz().cast(value)); } else { //new instance field.set(object, castDef.clazz().getConstructor(castDef.constructorParamClazz()) .newInstance(value)); } } else { if (JSONObject.NULL.equals(value)) { field.set(object, null); } else { field.set(object, parseFieldValue(field, value)); } } } catch (IllegalAccessException | IllegalArgumentException | JSONException e) { throw new HstoreParseException( HstoreParseException.HSTORE_COULD_NOT_INSTANTIATE + clazz.getCanonicalName(), e); } catch (InstantiationException e) { throw new HstoreParseException( HstoreParseException.HSTORE_COULD_NOT_INSTANTIATE + clazz.getCanonicalName(), e); } catch (InvocationTargetException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (NoSuchMethodException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SecurityException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ClassCastException e) { System.out.println("field: " + field.toString() + ", key: " + key); e.printStackTrace(); } } } return object; }
From source file:se.vgregion.dao.domain.patterns.repository.db.jpa.AbstractJpaRepository.java
/** * Get the actual type arguments a child class has used to extend a generic base class. * // w ww.jav a 2s . c om * @param childClass * the child class * @return a list of the raw classes for the actual type arguments. * * @see http://www.artima.com/weblogs/viewpost.jsp?thread=208860 */ private List<Class<? extends T>> getTypeArguments( @SuppressWarnings("rawtypes") Class<? extends AbstractJpaRepository> childClass) { Map<Type, Type> resolvedTypes = new HashMap<Type, Type>(); Type type = childClass; // start walking up the inheritance hierarchy until we hit this class while (!getClass(type).equals(AbstractJpaRepository.class)) { if (type instanceof Class) { // there is no useful information for us in raw types, so just keep going. type = ((Class<?>) type).getGenericSuperclass(); } else { ParameterizedType parameterizedType = (ParameterizedType) type; Class<?> rawType = (Class<?>) parameterizedType.getRawType(); Type[] actualTypeArguments = parameterizedType.getActualTypeArguments(); TypeVariable<?>[] typeParameters = rawType.getTypeParameters(); for (int i = 0; i < actualTypeArguments.length; i++) { resolvedTypes.put(typeParameters[i], actualTypeArguments[i]); } if (!rawType.equals(AbstractJpaRepository.class)) { type = rawType.getGenericSuperclass(); } } } // finally, for each actual type argument provided to baseClass, determine (if possible) // the raw class for that type argument. Type[] actualTypeArguments; if (type instanceof Class) { actualTypeArguments = ((Class<?>) type).getTypeParameters(); } else { actualTypeArguments = ((ParameterizedType) type).getActualTypeArguments(); } List<Class<? extends T>> typeArgumentsAsClasses = new ArrayList<Class<? extends T>>(); // resolve types by chasing down type variables. for (Type baseType : actualTypeArguments) { while (resolvedTypes.containsKey(baseType)) { baseType = resolvedTypes.get(baseType); } typeArgumentsAsClasses.add(getClass(baseType)); } return typeArgumentsAsClasses; }
From source file:com.google.api.server.spi.request.ServletRequestParamReader.java
private <T> Collection<T> deserializeCollection(Class<?> clazz, ParameterizedType collectionType, JsonNode nodeValue) throws IOException { @SuppressWarnings("unchecked") Class<? extends Collection<T>> collectionClass = (Class<? extends Collection<T>>) clazz; @SuppressWarnings("unchecked") Class<T> paramClass = (Class<T>) EndpointMethod .getClassFromType(collectionType.getActualTypeArguments()[0]); @SuppressWarnings("unchecked") Class<T[]> arrayClazz = (Class<T[]>) Array.newInstance(paramClass, 0).getClass(); Collection<T> collection = objectReader.forType(collectionClass).readValue(objectReader.createArrayNode()); if (nodeValue != null) { T[] array = objectReader.forType(arrayClazz).readValue(nodeValue); collection.addAll(Arrays.asList(array)); }//www.j a v a 2 s .c om return collection; }
From source file:org.sejda.cli.transformer.CliCommand.java
@SuppressWarnings("unchecked") protected Class<T> getCliArgumentsClass() { // returning T.class see http://www.artima.com/weblogs/viewpost.jsp?thread=208860 ParameterizedType parameterizedType = (ParameterizedType) getClass().getGenericSuperclass(); return (Class<T>) parameterizedType.getActualTypeArguments()[0]; }
From source file:org.evosuite.utils.generic.GenericAccessibleObject.java
/** * Maps type parameters in a type to their values. * /*from ww w . ja va 2s . c o m*/ * @param toMapType * Type possibly containing type arguments * @param typeAndParams * must be either ParameterizedType, or (in case there are no * type arguments, or it's a raw type) Class * @return toMapType, but with type parameters from typeAndParams replaced. */ protected Type mapTypeParameters(Type toMapType, Type typeAndParams) { if (isMissingTypeParameters(typeAndParams)) { logger.debug("Is missing type parameters, so erasing types"); return GenericTypeReflector.erase(toMapType); } else { VarMap varMap = new VarMap(); Type handlingTypeAndParams = typeAndParams; while (handlingTypeAndParams instanceof ParameterizedType) { ParameterizedType pType = (ParameterizedType) handlingTypeAndParams; Class<?> clazz = (Class<?>) pType.getRawType(); // getRawType should always be Class varMap.addAll(clazz.getTypeParameters(), pType.getActualTypeArguments()); handlingTypeAndParams = pType.getOwnerType(); } varMap.addAll(getTypeVariableMap()); return varMap.map(toMapType); } }
From source file:org.debux.webmotion.jpa.GenericDAO.java
/** * Complete entity with parameters. Try to convert parameter, if the type not * match. To create an association on entity, you must pass only identifier. * /* w w w. jav a 2 s . c om*/ * @param entity entity * @param parameters parameters * @return entity completed */ protected IdentifiableEntity extract(IdentifiableEntity entity, Parameters parameters) { try { Field[] fields = entityClass.getDeclaredFields(); for (Field field : fields) { String name = field.getName(); Class<?> type = field.getType(); Object[] values = parameters.get(name); // The identifier can't be set if (!IdentifiableEntity.ATTRIBUTE_NAME_ID.equals(name) && values != null) { if (values.length == 0) { // Null value beanUtil.setProperty(entity, name, null); } else if (type.isAnnotationPresent(javax.persistence.Entity.class)) { // Association List<Object> references = new ArrayList<Object>(values.length); for (Object value : values) { Object reference = manager.find(type, value); if (reference != null) { references.add(reference); } } Object converted = null; if (List.class.isAssignableFrom(type)) { converted = references; } else if (Set.class.isAssignableFrom(type)) { converted = new HashSet<Object>(references); } else if (SortedSet.class.isAssignableFrom(type)) { converted = new TreeSet<Object>(references); } else if (type.isArray()) { converted = references.toArray(); } else if (Map.class.isAssignableFrom(type)) { String keyName = IdentifiableEntity.ATTRIBUTE_NAME_ID; MapKey annotation = type.getAnnotation(MapKey.class); if (annotation != null) { String annotationName = annotation.name(); if (annotationName != null && !annotationName.isEmpty()) { keyName = annotationName; } } Map<Object, Object> map = new HashMap<Object, Object>(); for (Object object : references) { Object key = propertyUtils.getProperty(object, keyName); map.put(key, object); } converted = map; } else if (!references.isEmpty()) { converted = references.get(0); } beanUtil.setProperty(entity, name, converted); } else { // Basic object if (Collection.class.isAssignableFrom(type)) { Class convertType = String.class; Type genericType = field.getGenericType(); if (genericType != null && genericType instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType) genericType; convertType = (Class) parameterizedType.getActualTypeArguments()[0]; } Collection<Object> collection = null; if (Set.class.isAssignableFrom(type)) { collection = new HashSet<Object>(); } else if (SortedSet.class.isAssignableFrom(type)) { collection = new TreeSet(); } else { collection = new ArrayList<Object>(); } for (Object object : values) { Object convertedObject = convertUtils.convert(object, convertType); collection.add(convertedObject); } beanUtil.setProperty(entity, name, collection); } else if (Map.class.isAssignableFrom(type)) { throw new UnsupportedOperationException( "Map is not supported, you must create a specific entity."); } else { Object converted = convertUtils.convert(values, type); beanUtil.setProperty(entity, name, converted); } } } } return entity; } catch (IllegalAccessException iae) { throw new WebMotionException("Error during create instance", iae); } catch (InvocationTargetException ite) { throw new WebMotionException("Error during set field on instance", ite); } catch (NoSuchMethodException nsme) { throw new WebMotionException("Error during set field on instance", nsme); } }
From source file:de.escalon.hypermedia.spring.AffordanceBuilderFactory.java
private boolean containsCollection(Type genericReturnType) { final boolean ret; if (genericReturnType instanceof ParameterizedType) { ParameterizedType t = (ParameterizedType) genericReturnType; Type rawType = t.getRawType(); Assert.state(rawType instanceof Class<?>, "raw type is not a Class: " + rawType.toString()); Class<?> cls = (Class<?>) rawType; if (HttpEntity.class.isAssignableFrom(cls)) { Type[] typeArguments = t.getActualTypeArguments(); ret = containsCollection(typeArguments[0]); } else if (Resources.class.isAssignableFrom(cls) || Collection.class.isAssignableFrom(cls)) { ret = true;// w ww. j av a2s.c om } else { ret = false; } } else if (genericReturnType instanceof GenericArrayType) { ret = true; } else if (genericReturnType instanceof WildcardType) { WildcardType t = (WildcardType) genericReturnType; ret = containsCollection(getBound(t.getLowerBounds())) || containsCollection(getBound(t.getUpperBounds())); } else if (genericReturnType instanceof TypeVariable) { ret = false; } else if (genericReturnType instanceof Class) { Class<?> cls = (Class<?>) genericReturnType; ret = Resources.class.isAssignableFrom(cls) || Collection.class.isAssignableFrom(cls); } else { ret = false; } return ret; }
From source file:org.debux.webmotion.server.handler.ExecutorParametersConvertorHandler.java
protected Object convert(ParameterTree parameterTree, Class<?> type, Type genericType) throws Exception { Object result = null;// www.jav a2 s.co m if (parameterTree == null) { return null; } if (genericType == null) { genericType = type.getGenericSuperclass(); } Map<String, List<ParameterTree>> parameterArray = parameterTree.getArray(); Map<String, ParameterTree> parameterObject = parameterTree.getObject(); Object value = parameterTree.getValue(); Converter lookup = converter.lookup(type); if (lookup != null) { // converter found, use it result = lookup.convert(type, value); return result; } // Manage enums if (type.isEnum()) { Object name = value == null ? null : ((Object[]) value)[0]; if (name != null) { result = Enum.valueOf((Class<? extends Enum>) type, name.toString()); } // Manage collection } else if (Collection.class.isAssignableFrom(type)) { Collection instance; if (type.isInterface()) { if (List.class.isAssignableFrom(type)) { instance = new ArrayList(); } else if (Set.class.isAssignableFrom(type)) { instance = new HashSet(); } else if (SortedSet.class.isAssignableFrom(type)) { instance = new TreeSet(); } else { instance = new ArrayList(); } } else { instance = (Collection) type.newInstance(); } Class convertType = String.class; if (genericType != null && genericType instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType) genericType; convertType = (Class) parameterizedType.getActualTypeArguments()[0]; } if (parameterObject != null) { for (Map.Entry<String, ParameterTree> entry : parameterObject.entrySet()) { ParameterTree object = entry.getValue(); Object converted = convert(object, convertType, null); instance.add(converted); } } else { Object[] tab = (Object[]) value; for (Object object : tab) { Object converted = converter.convert(object, convertType); instance.add(converted); } } result = instance; // Manage map } else if (Map.class.isAssignableFrom(type)) { Map instance; if (type.isInterface()) { if (SortedMap.class.isAssignableFrom(type)) { instance = new TreeMap(); } else { instance = new HashMap(); } } else { instance = (Map) type.newInstance(); } Class convertKeyType = String.class; Class convertValueType = String.class; if (genericType != null && genericType instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType) genericType; convertKeyType = (Class) parameterizedType.getActualTypeArguments()[0]; convertValueType = (Class) parameterizedType.getActualTypeArguments()[1]; } for (Map.Entry<String, ParameterTree> entry : parameterObject.entrySet()) { String mapKey = entry.getKey(); ParameterTree mapValue = entry.getValue(); Object convertedKey = converter.convert(mapKey, convertKeyType); Object convertedValue = convert(mapValue, convertValueType, null); instance.put(convertedKey, convertedValue); } result = instance; // Manage simple object } else if (type.isArray()) { Class<?> componentType = type.getComponentType(); if (parameterObject != null) { Object[] tabConverted = (Object[]) Array.newInstance(componentType, parameterObject.size()); result = tabConverted; int index = 0; for (Map.Entry<String, ParameterTree> entry : parameterObject.entrySet()) { ParameterTree object = entry.getValue(); Object objectConverted = convert(object, componentType, null); tabConverted[index] = objectConverted; index++; } } else { Object[] tab = (Object[]) value; Object[] tabConverted = (Object[]) Array.newInstance(componentType, tab.length); result = tabConverted; for (int index = 0; index < tab.length; index++) { Object object = tab[index]; Object objectConverted = converter.convert(object, componentType); tabConverted[index] = objectConverted; } } } else if (value instanceof UploadFile) { if (File.class.isAssignableFrom(type)) { UploadFile uploadFile = (UploadFile) value; result = uploadFile.getFile(); } else { result = value; } // Manage simple object } else { Object instance = type.newInstance(); boolean one = false; if (parameterObject != null) { for (Map.Entry<String, ParameterTree> attribut : parameterObject.entrySet()) { String attributeName = attribut.getKey(); ParameterTree attributeValue = attribut.getValue(); boolean writeable = propertyUtils.isWriteable(instance, attributeName); if (writeable) { one = true; Field field = FieldUtils.getField(type, attributeName, true); Class<?> attributeType = field.getType(); genericType = field.getGenericType(); Object attributeConverted = convert(attributeValue, attributeType, genericType); beanUtil.setProperty(instance, attributeName, attributeConverted); } } } if (parameterArray != null) { for (Map.Entry<String, List<ParameterTree>> entry : parameterArray.entrySet()) { String attributeName = entry.getKey(); List<ParameterTree> attributeValues = entry.getValue(); boolean writeable = propertyUtils.isWriteable(instance, attributeName); if (writeable) { one = true; Field field = FieldUtils.getField(type, attributeName, true); Class<?> attributeType = field.getType(); genericType = field.getGenericType(); Object attributeConverted = convert(attributeValues, attributeType, genericType); beanUtil.setProperty(instance, attributeName, attributeConverted); } } } if (one) { result = instance; } else { result = null; } } return result; }