List of usage examples for java.lang.reflect ParameterizedType getRawType
Type getRawType();
From source file:org.soybeanMilk.core.bean.DefaultGenericConverter.java
/** * ?{@linkplain ParameterizedType}//w w w . j a v a2s . c om * @param array * @param type * @return * @throws ConvertException * @date 2012-5-14 */ protected Object convertArrayToParameterrizedType(Object array, ParameterizedType type) throws ConvertException { Object result = null; Type rt = type.getRawType(); Type[] atas = type.getActualTypeArguments(); if (SbmUtils.isClassType(rt)) { Class<?> actualType = SbmUtils.narrowToClass(rt); //List<T> if (isAncestorType(List.class, actualType)) { result = convertArrayToList(array, actualType, atas[0]); } //Set<T> else if (isAncestorType(Set.class, actualType)) { List<?> list = convertArrayToList(array, List.class, atas[0]); result = listToSet(list, actualType); } else result = converterNotFoundThrow(array.getClass(), type); } else result = converterNotFoundThrow(array.getClass(), type); return result; }
From source file:org.soybeanMilk.core.bean.DefaultGenericConverter.java
/** * ?{@linkplain ParameterizedType}//from w ww. jav a 2 s .c o m * @param pvm * @param type * @return * @throws ConvertException * @date 2012-5-14 */ protected Object convertPropertyValueMapToParameterrizedType(PropertyValueMap pvm, ParameterizedType type) throws ConvertException { Object result = null; Type rt = type.getRawType(); Type[] atas = type.getActualTypeArguments(); if (SbmUtils.isClassType(rt)) { Class<?> actualType = SbmUtils.narrowToClass(rt); //List<T> if (isAncestorType(List.class, actualType)) { result = convertPropertyValueMapToList(pvm, actualType, atas[0]); } //Set<T> else if (isAncestorType(Set.class, actualType)) { List<?> tmpRe = convertPropertyValueMapToList(pvm, List.class, atas[0]); result = listToSet(tmpRe, actualType); } //Map<K, V> else if (isAncestorType(Map.class, actualType)) { result = convertPropertyValueMapToMap(pvm, actualType, atas[0], atas[1]); } else result = converterNotFoundThrow(pvm.getClass(), type); } else result = converterNotFoundThrow(pvm.getClass(), type); return result; }
From source file:org.nextframework.controller.ExtendedBeanWrapper.java
private Type getPropertyType(PropertyTokenHolder tokens) { String propertyName = tokens.canonicalName; PropertyDescriptor pd = getPropertyDescriptorInternal(tokens.actualName); if (pd == null || pd.getReadMethod() == null) { throw new NotReadablePropertyException(getRootClass(), this.nestedPath + propertyName); }// w w w . j a va 2 s. c om if (logger.isDebugEnabled()) logger.debug("About to invoke read method [" + pd.getReadMethod() + "] on object of class [" + this.object.getClass().getName() + "]"); try { Type type = pd.getReadMethod().getGenericReturnType(); if (tokens.keys != null) { // apply indexes and map keys for (int i = 0; i < tokens.keys.length; i++) { if (type == null) { throw new NullValueInNestedPathException(getRootClass(), this.nestedPath + propertyName, "Cannot access indexed value of property referenced in indexed " + "property path '" + propertyName + "': returned null"); } else if (type instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType) type; Class clazz = (Class) parameterizedType.getRawType(); if (Map.class.isAssignableFrom(clazz)) { type = parameterizedType.getActualTypeArguments()[1]; } else if (Collection.class.isAssignableFrom(clazz)) { type = parameterizedType.getActualTypeArguments()[0]; } else { throw new RuntimeException("Tipo desconhecido " + parameterizedType); } } else if (type instanceof Class && ((Class) type).isArray()) { return type; } else { throw new RuntimeException("Implementar converso!!!"); } } } return type; } catch (IndexOutOfBoundsException ex) { throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName, "Index of out of bounds in property path '" + propertyName + "'", ex); } catch (NumberFormatException ex) { throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName, "Invalid index in property path '" + propertyName + "'", ex); } }
From source file:com.evolveum.midpoint.prism.parser.PrismBeanConverter.java
public <T> T unmarshall(MapXNode xnode, Class<T> beanClass) throws SchemaException { if (PolyStringType.class.equals(beanClass)) { PolyString polyString = unmarshalPolyString(xnode); return (T) polyString; // violates the method interface but ... TODO fix it } else if (ProtectedStringType.class.equals(beanClass)) { ProtectedStringType protectedType = new ProtectedStringType(); XNodeProcessorUtil.parseProtectedType(protectedType, xnode, prismContext); return (T) protectedType; } else if (ProtectedByteArrayType.class.equals(beanClass)) { ProtectedByteArrayType protectedType = new ProtectedByteArrayType(); XNodeProcessorUtil.parseProtectedType(protectedType, xnode, prismContext); return (T) protectedType; } else if (SchemaDefinitionType.class.equals(beanClass)) { SchemaDefinitionType schemaDefType = unmarshalSchemaDefinitionType(xnode); return (T) schemaDefType; } else if (prismContext.getSchemaRegistry().determineDefinitionFromClass(beanClass) != null) { return (T) prismContext.getXnodeProcessor().parseObject(xnode).asObjectable(); } else if (XmlAsStringType.class.equals(beanClass)) { // reading a string represented a XML-style content // used e.g. when reading report templates (embedded XML) // A necessary condition: there may be only one map entry. if (xnode.size() > 1) { throw new SchemaException("Map with more than one item cannot be parsed as a string: " + xnode); } else if (xnode.isEmpty()) { return (T) new XmlAsStringType(); } else {/* www .j av a2 s .co m*/ Map.Entry<QName, XNode> entry = xnode.entrySet().iterator().next(); DomParser domParser = prismContext.getParserDom(); String value = domParser.serializeToString(entry.getValue(), entry.getKey()); return (T) new XmlAsStringType(value); } } T bean; Set<String> keysToParse; // only these keys will be parsed (null if all) if (SearchFilterType.class.isAssignableFrom(beanClass)) { keysToParse = Collections.singleton("condition"); // TODO fix this BRUTAL HACK - it is here because of c:ConditionalSearchFilterType bean = (T) unmarshalSearchFilterType(xnode, (Class<? extends SearchFilterType>) beanClass); } else { keysToParse = null; try { bean = beanClass.newInstance(); } catch (InstantiationException e) { throw new SystemException("Cannot instantiate bean of type " + beanClass + ": " + e.getMessage(), e); } catch (IllegalAccessException e) { throw new SystemException("Cannot instantiate bean of type " + beanClass + ": " + e.getMessage(), e); } } if (ProtectedDataType.class.isAssignableFrom(beanClass)) { ProtectedDataType protectedDataType = null; if (bean instanceof ProtectedStringType) { protectedDataType = new ProtectedStringType(); } else if (bean instanceof ProtectedByteArrayType) { protectedDataType = new ProtectedByteArrayType(); } else { throw new SchemaException("Unexpected subtype of protected data type: " + bean.getClass()); } XNodeProcessorUtil.parseProtectedType(protectedDataType, xnode, prismContext); return (T) protectedDataType; } for (Entry<QName, XNode> entry : xnode.entrySet()) { QName key = entry.getKey(); if (keysToParse != null && !keysToParse.contains(key.getLocalPart())) { continue; } XNode xsubnode = entry.getValue(); String propName = key.getLocalPart(); Field field = inspector.findPropertyField(beanClass, propName); Method propertyGetter = null; if (field == null) { propertyGetter = inspector.findPropertyGetter(beanClass, propName); } Method elementMethod = null; Object objectFactory = null; if (field == null && propertyGetter == null) { // We have to try to find a more generic field, such as xsd:any or substitution element // check for global element definition first Class objectFactoryClass = inspector.getObjectFactoryClass(beanClass.getPackage()); objectFactory = instantiateObjectFactory(objectFactoryClass); elementMethod = inspector.findElementMethodInObjectFactory(objectFactoryClass, propName); if (elementMethod == null) { // Check for "any" method elementMethod = inspector.findAnyMethod(beanClass); if (elementMethod == null) { String m = "No field " + propName + " in class " + beanClass + " (and no element method in object factory too)"; if (mode == XNodeProcessorEvaluationMode.COMPAT) { LOGGER.warn("{}", m); continue; } else { throw new SchemaException(m); } } unmarshallToAny(bean, elementMethod, key, xsubnode); continue; } field = inspector.lookupSubstitution(beanClass, elementMethod); if (field == null) { // Check for "any" field field = inspector.findAnyField(beanClass); if (field == null) { elementMethod = inspector.findAnyMethod(beanClass); if (elementMethod == null) { String m = "No field " + propName + " in class " + beanClass + " (and no element method in object factory too)"; if (mode == XNodeProcessorEvaluationMode.COMPAT) { LOGGER.warn("{}", m); continue; } else { throw new SchemaException(m); } } unmarshallToAny(bean, elementMethod, key, xsubnode); continue; // throw new SchemaException("No field "+propName+" in class "+beanClass+" (no suitable substitution and no 'any' field)"); } unmarshallToAny(bean, field, key, xsubnode); continue; } } boolean storeAsRawType; if (elementMethod != null) { storeAsRawType = elementMethod.getAnnotation(Raw.class) != null; } else if (propertyGetter != null) { storeAsRawType = propertyGetter.getAnnotation(Raw.class) != null; } else { storeAsRawType = field.getAnnotation(Raw.class) != null; } String fieldName; if (field != null) { fieldName = field.getName(); } else { fieldName = propName; } Method setter = inspector.findSetter(beanClass, fieldName); Method getter = null; boolean wrapInJaxbElement = false; Class<?> paramType = null; if (setter == null) { // No setter. But if the property is multi-value we need to look // for a getter that returns a collection (Collection<Whatever>) getter = inspector.findPropertyGetter(beanClass, fieldName); if (getter == null) { String m = "Cannot find setter or getter for field " + fieldName + " in " + beanClass; if (mode == XNodeProcessorEvaluationMode.COMPAT) { LOGGER.warn("{}", m); continue; } else { throw new SchemaException(m); } } Class<?> getterReturnType = getter.getReturnType(); if (!Collection.class.isAssignableFrom(getterReturnType)) { throw new SchemaException("Cannot find getter for field " + fieldName + " in " + beanClass + " does not return collection, cannot use it to set value"); } Type genericReturnType = getter.getGenericReturnType(); Type typeArgument = getTypeArgument(genericReturnType, "for field " + fieldName + " in " + beanClass + ", cannot determine collection type"); // System.out.println("type argument " + typeArgument); if (typeArgument instanceof Class) { paramType = (Class<?>) typeArgument; } else if (typeArgument instanceof ParameterizedType) { ParameterizedType paramTypeArgument = (ParameterizedType) typeArgument; Type rawTypeArgument = paramTypeArgument.getRawType(); if (rawTypeArgument.equals(JAXBElement.class)) { // This is the case of Collection<JAXBElement<....>> wrapInJaxbElement = true; Type innerTypeArgument = getTypeArgument(typeArgument, "for field " + fieldName + " in " + beanClass + ", cannot determine collection type (inner type argument)"); if (innerTypeArgument instanceof Class) { // This is the case of Collection<JAXBElement<Whatever>> paramType = (Class<?>) innerTypeArgument; } else if (innerTypeArgument instanceof WildcardType) { // This is the case of Collection<JAXBElement<?>> // we need to exctract the specific type from the factory method if (elementMethod == null) { // TODO: TEMPORARY CODE!!!!!!!!!! fix in 3.1 [med] Class objectFactoryClass = inspector.getObjectFactoryClass(beanClass.getPackage()); objectFactory = instantiateObjectFactory(objectFactoryClass); elementMethod = inspector.findElementMethodInObjectFactory(objectFactoryClass, propName); if (elementMethod == null) { throw new IllegalArgumentException( "Wildcard type in JAXBElement field specification and no factory method found for field " + fieldName + " in " + beanClass + ", cannot determine collection type (inner type argument)"); } } Type factoryMethodGenericReturnType = elementMethod.getGenericReturnType(); Type factoryMethodTypeArgument = getTypeArgument(factoryMethodGenericReturnType, "in factory method " + elementMethod + " return type for field " + fieldName + " in " + beanClass + ", cannot determine collection type"); if (factoryMethodTypeArgument instanceof Class) { // This is the case of JAXBElement<Whatever> paramType = (Class<?>) factoryMethodTypeArgument; if (Object.class.equals(paramType) && !storeAsRawType) { throw new IllegalArgumentException("Factory method " + elementMethod + " type argument is Object (and not @Raw) for field " + fieldName + " in " + beanClass + ", property " + propName); } } else { throw new IllegalArgumentException( "Cannot determine factory method return type, got " + factoryMethodTypeArgument + " - for field " + fieldName + " in " + beanClass + ", cannot determine collection type (inner type argument)"); } } else { throw new IllegalArgumentException("Ejha! " + innerTypeArgument + " " + innerTypeArgument.getClass() + " from " + getterReturnType + " from " + fieldName + " in " + propName + " " + beanClass); } } else { // The case of Collection<Whatever<Something>> if (rawTypeArgument instanceof Class) { paramType = (Class<?>) rawTypeArgument; } else { throw new IllegalArgumentException("EH? Eh!? " + typeArgument + " " + typeArgument.getClass() + " from " + getterReturnType + " from " + fieldName + " in " + propName + " " + beanClass); } } } else { throw new IllegalArgumentException( "EH? " + typeArgument + " " + typeArgument.getClass() + " from " + getterReturnType + " from " + fieldName + " in " + propName + " " + beanClass); } } else { Class<?> setterType = setter.getParameterTypes()[0]; if (JAXBElement.class.equals(setterType)) { // TODO some handling for the returned generic parameter types Type[] genericTypes = setter.getGenericParameterTypes(); if (genericTypes.length != 1) { throw new IllegalArgumentException("Too lazy to handle this."); } Type genericType = genericTypes[0]; if (genericType instanceof ParameterizedType) { Type actualType = getTypeArgument(genericType, "add some description"); if (actualType instanceof WildcardType) { if (elementMethod == null) { Class objectFactoryClass = inspector.getObjectFactoryClass(beanClass.getPackage()); objectFactory = instantiateObjectFactory(objectFactoryClass); elementMethod = inspector.findElementMethodInObjectFactory(objectFactoryClass, propName); } // This is the case of Collection<JAXBElement<?>> // we need to exctract the specific type from the factory method if (elementMethod == null) { throw new IllegalArgumentException( "Wildcard type in JAXBElement field specification and no facotry method found for field " + fieldName + " in " + beanClass + ", cannot determine collection type (inner type argument)"); } Type factoryMethodGenericReturnType = elementMethod.getGenericReturnType(); Type factoryMethodTypeArgument = getTypeArgument(factoryMethodGenericReturnType, "in factory method " + elementMethod + " return type for field " + fieldName + " in " + beanClass + ", cannot determine collection type"); if (factoryMethodTypeArgument instanceof Class) { // This is the case of JAXBElement<Whatever> paramType = (Class<?>) factoryMethodTypeArgument; if (Object.class.equals(paramType) && !storeAsRawType) { throw new IllegalArgumentException("Factory method " + elementMethod + " type argument is Object (without @Raw) for field " + fieldName + " in " + beanClass + ", property " + propName); } } else { throw new IllegalArgumentException( "Cannot determine factory method return type, got " + factoryMethodTypeArgument + " - for field " + fieldName + " in " + beanClass + ", cannot determine collection type (inner type argument)"); } } } // Class enclosing = paramType.getEnclosingClass(); // Class clazz = paramType.getClass(); // Class declaring = paramType.getDeclaringClass(); wrapInJaxbElement = true; } else { paramType = setterType; } } if (Element.class.isAssignableFrom(paramType)) { // DOM! throw new IllegalArgumentException("DOM not supported in field " + fieldName + " in " + beanClass); } //check for subclasses??? if (!storeAsRawType && xsubnode.getTypeQName() != null) { Class explicitParamType = getSchemaRegistry().determineCompileTimeClass(xsubnode.getTypeQName()); if (explicitParamType == null) { explicitParamType = XsdTypeMapper.toJavaTypeIfKnown(xsubnode.getTypeQName()); } if (explicitParamType != null) { paramType = explicitParamType; } } if (!(xsubnode instanceof ListXNode) && Object.class.equals(paramType) && !storeAsRawType) { throw new IllegalArgumentException( "Object property (without @Raw) not supported in field " + fieldName + " in " + beanClass); } String paramNamespace = inspector.determineNamespace(paramType); boolean problem = false; Object propValue = null; Collection<Object> propValues = null; if (xsubnode instanceof ListXNode) { ListXNode xlist = (ListXNode) xsubnode; if (setter != null) { try { propValue = convertSinglePropValue(xsubnode, fieldName, paramType, storeAsRawType, beanClass, paramNamespace); } catch (SchemaException e) { problem = processSchemaException(e, xsubnode); } } else { // No setter, we have to use collection getter propValues = new ArrayList<>(xlist.size()); for (XNode xsubsubnode : xlist) { try { propValues.add(convertSinglePropValue(xsubsubnode, fieldName, paramType, storeAsRawType, beanClass, paramNamespace)); } catch (SchemaException e) { problem = processSchemaException(e, xsubsubnode); } } } } else { try { propValue = convertSinglePropValue(xsubnode, fieldName, paramType, storeAsRawType, beanClass, paramNamespace); } catch (SchemaException e) { problem = processSchemaException(e, xsubnode); } } if (setter != null) { try { setter.invoke(bean, prepareValueToBeStored(propValue, wrapInJaxbElement, objectFactory, elementMethod, propName, beanClass)); } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { throw new SystemException("Cannot invoke setter " + setter + " on bean of type " + beanClass + ": " + e.getMessage(), e); } } else if (getter != null) { Object getterReturn; Collection<Object> col; try { getterReturn = getter.invoke(bean); } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { throw new SystemException("Cannot invoke getter " + getter + " on bean of type " + beanClass + ": " + e.getMessage(), e); } try { col = (Collection<Object>) getterReturn; } catch (ClassCastException e) { throw new SystemException("Getter " + getter + " on bean of type " + beanClass + " returned " + getterReturn + " instead of collection"); } if (propValue != null) { col.add(prepareValueToBeStored(propValue, wrapInJaxbElement, objectFactory, elementMethod, propName, beanClass)); } else if (propValues != null) { for (Object propVal : propValues) { col.add(prepareValueToBeStored(propVal, wrapInJaxbElement, objectFactory, elementMethod, propName, beanClass)); } } else if (!problem) { throw new IllegalStateException("Strange. Multival property " + propName + " in " + beanClass + " produced null values list, parsed from " + xnode); } checkJaxbElementConsistence(col); } else { throw new IllegalStateException("Uh? No setter nor getter."); } } if (prismContext != null && bean instanceof Revivable) { ((Revivable) bean).revive(prismContext); } return bean; }
From source file:org.openmrs.module.sync.api.db.hibernate.HibernateSyncInterceptor.java
/** * Checks the collection to see if it is a collection of supported types. If so, then it returns * appropriate normalizer. Note, this handles maps too. * * @param object/*from ww w . ja v a 2 s . c o m*/ * @param propertyName * @return a Normalizer for the given type or null if not a safe type * @throws NoSuchFieldException * @throws SecurityException */ private Normalizer isCollectionOfSafeTypes(OpenmrsObject object, String propertyName) throws SecurityException, NoSuchFieldException { try { java.lang.reflect.ParameterizedType collectionType = ((java.lang.reflect.ParameterizedType) object .getClass().getDeclaredField(propertyName).getGenericType()); if (Map.class.isAssignableFrom((Class) collectionType.getRawType())) { //this is a map; Map<K,V>: verify that K and V are of types we know how to process java.lang.reflect.Type keyType = collectionType.getActualTypeArguments()[0]; java.lang.reflect.Type valueType = collectionType.getActualTypeArguments()[1]; Normalizer keyNormalizer = SyncUtil.getNormalizer((Class) keyType); Normalizer valueNormalizer = SyncUtil.getNormalizer((Class) valueType); if (keyNormalizer != null && valueNormalizer != null) { return SyncUtil.getNormalizer((Class) collectionType.getRawType()); } else { return null; } } else { //this is some other collection, so just get a normalizer for its return SyncUtil.getNormalizer((Class) (collectionType.getActualTypeArguments()[0])); } } catch (Throwable t) { // might get here if the property is on a superclass to the object log.trace("Unable to get collection field: " + propertyName + " from object " + object.getClass() + " for some reason", t); } // on errors just return null return null; }
From source file:co.paralleluniverse.galaxy.core.Cache.java
private static boolean isVoidLineFunction(Class<?> clazz) { if (clazz == null) return false; for (java.lang.reflect.Type iface : clazz.getGenericInterfaces()) { if (iface instanceof java.lang.reflect.ParameterizedType) { java.lang.reflect.ParameterizedType pt = (java.lang.reflect.ParameterizedType) iface; if (pt.getRawType() == LineFunction.class) return (pt.getActualTypeArguments()[0] == Void.class); boolean r = isVoidLineFunction((Class) pt.getRawType()); if (r) return true; } else if (iface == LineFunction.class) return false; boolean r = isVoidLineFunction((Class) iface); if (r)/*from w ww . j a va 2 s . com*/ return true; } return isVoidLineFunction(clazz.getSuperclass()); }
From source file:org.apache.axis2.wsdl.codegen.emitter.AxisServiceBasedMultiLanguageEmitter.java
private String getParameterName(Type type, List existingParamNames) { String paramName = null;/*from w ww . j ava 2s . c om*/ if (type instanceof Class) { Class classType = (Class) type; if (classType.isArray()) { paramName = getParameterName(classType.getComponentType(), existingParamNames); } else { String className = classType.getName(); if (className.lastIndexOf(".") > 0) { className = className.substring(className.lastIndexOf(".") + 1); } paramName = JavaUtils.xmlNameToJavaIdentifier(className); if (existingParamNames.contains(paramName)) { paramName = paramName + existingParamNames.size(); } existingParamNames.add(paramName); } } else if (type instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType) type; paramName = getParameterName(parameterizedType.getRawType(), existingParamNames); } return paramName; }
From source file:com.clark.func.Functions.java
/** * <p>/*w ww. j ava2 s . co m*/ * Type-checking method of convenience. * </p> * * @param parameterizedType * @return */ private static Class<?> getRawType(ParameterizedType parameterizedType) { Type rawType = parameterizedType.getRawType(); // check if raw type is a Class object // not currently necessary, but since the return type is Type instead of // Class, there's enough reason to believe that future versions of Java // may return other Type implementations. And type-safety checking is // rarely a bad idea. if (!(rawType instanceof Class<?>)) { throw new IllegalStateException("Wait... What!? Type of rawType: " + rawType); } return (Class<?>) rawType; }