List of usage examples for java.lang.reflect ParameterizedType getRawType
Type getRawType();
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. * /*ww w . jav a 2 s.c o m*/ * @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:info.archinnov.achilles.internal.metadata.parsing.PropertyParser.java
@SuppressWarnings("unchecked") public <T> Class<T> getClassFromType(Type type) { log.debug("Infer class from type {}", type); if (type instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType) type; return (Class<T>) parameterizedType.getRawType(); } else if (type instanceof Class) { return (Class<T>) type; } else {/* ww w .j av a2s . c om*/ throw new IllegalArgumentException("Cannot determine java class of type '" + type + "'"); } }
From source file:org.evosuite.utils.generic.GenericTypeInference.java
private void addToMap(ParameterizedType type, Type actualType, Map<TypeVariable<?>, Type> typeMap) { Type[] parameterTypes = type.getActualTypeArguments(); TypeVariable<?>[] variables = ((Class<?>) type.getRawType()).getTypeParameters(); for (int i = 0; i < parameterTypes.length; i++) { typeMap.put(variables[i], parameterTypes[i]); }/* ww w.j a v a 2 s . c o m*/ }
From source file:com.github.hateoas.forms.spring.xhtml.XhtmlResourceMessageConverter.java
public Object read(java.lang.reflect.Type type, Class<?> contextClass, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException { final Class clazz; if (type instanceof Class) { clazz = (Class) type;//from www .ja v a 2s . c o m } else if (type instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType) type; Type rawType = parameterizedType.getRawType(); if (rawType instanceof Class) { clazz = (Class) rawType; } else { throw new IllegalArgumentException("unexpected raw type " + rawType); } } else { throw new IllegalArgumentException("unexpected type " + type); } return readInternal(clazz, inputMessage); }
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 ww . j a v a 2 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.openmrs.module.sync.SyncUtil.java
public static Object valForField(String fieldName, String fieldVal, ArrayList<Field> allFields, Node n) { Object o = null;/* w w w.j a v a2s.c o m*/ // the String value on the node specifying the "type" String nodeDefinedClassName = null; if (n != null) { Node tmpNode = n.getAttributes().getNamedItem("type"); if (tmpNode != null) nodeDefinedClassName = tmpNode.getTextContent(); } // TODO: Speed up sync by passing in a Map of String fieldNames instead of list of Fields ? // TODO: Speed up sync by returning after "o" is first set? Or are we doing "last field wins" ? for (Field f : allFields) { //log.debug("field is " + f.getName()); if (f.getName().equals(fieldName)) { Class classType = null; String className = f.getGenericType().toString(); // the string class name for the actual field // if its a collection, set, list, etc if (ParameterizedType.class.isAssignableFrom(f.getGenericType().getClass())) { ParameterizedType pType = (ParameterizedType) f.getGenericType(); classType = (Class) pType.getRawType(); // can this be anything but Class at this point?! } if (className.startsWith("class ")) { className = className.substring("class ".length()); classType = (Class) f.getGenericType(); } else { log.trace("Abnormal className for " + f.getGenericType()); } if (classType == null) { if ("int".equals(className)) { return new Integer(fieldVal); } else if ("long".equals(className)) { return new Long(fieldVal); } else if ("double".equals(className)) { return new Double(fieldVal); } else if ("float".equals(className)) { return new Float(fieldVal); } else if ("boolean".equals(className)) { return new Boolean(fieldVal); } else if ("byte".equals(className)) { return new Byte(fieldVal); } else if ("short".equals(className)) { return new Short(fieldVal); } } // we have to explicitly create a new value object here because all we have is a string - won't know how to convert if (OpenmrsObject.class.isAssignableFrom(classType)) { o = getOpenmrsObj(className, fieldVal); } else if ("java.lang.Integer".equals(className) && !("integer".equals(nodeDefinedClassName) || "java.lang.Integer".equals(nodeDefinedClassName))) { // if we're dealing with a field like PersonAttributeType.foreignKey, the actual value was changed from // an integer to a uuid by the HibernateSyncInterceptor. The nodeDefinedClassName is the node.type which is the // actual classname as defined by the PersonAttributeType.format. However, the field.getClassName is // still an integer because thats what the db stores. we need to convert the uuid to the pk integer and return it OpenmrsObject obj = getOpenmrsObj(nodeDefinedClassName, fieldVal); o = obj.getId(); } else if ("java.lang.String".equals(className) && !("text".equals(nodeDefinedClassName) || "string".equals(nodeDefinedClassName) || "java.lang.String".equals(nodeDefinedClassName) || "integer".equals(nodeDefinedClassName) || "java.lang.Integer".equals(nodeDefinedClassName) || fieldVal.isEmpty())) { // if we're dealing with a field like PersonAttribute.value, the actual value was changed from // a string to a uuid by the HibernateSyncInterceptor. The nodeDefinedClassName is the node.type which is the // actual classname as defined by the PersonAttributeType.format. However, the field.getClassName is // still String because thats what the db stores. we need to convert the uuid to the pk integer/string and return it OpenmrsObject obj = getOpenmrsObj(nodeDefinedClassName, fieldVal); if (obj == null) { if (StringUtils.hasText(fieldVal)) { // If we make it here, and we are dealing with person attribute values, then just return the string value as-is if (PersonAttribute.class.isAssignableFrom(f.getDeclaringClass()) && "value".equals(f.getName())) { o = fieldVal; } else { // throw a warning if we're having trouble converting what should be a valid value log.error("Unable to convert value '" + fieldVal + "' into a " + nodeDefinedClassName); throw new SyncException("Unable to convert value '" + fieldVal + "' into a " + nodeDefinedClassName); } } else { // if fieldVal is empty, just save an empty string here too o = ""; } } else { o = obj.getId().toString(); // call toString so the class types match when looking up the setter } } else if (Collection.class.isAssignableFrom(classType)) { // this is a collection of items. this is intentionally not in the convertStringToObject method Collection tmpCollection = null; if (Set.class.isAssignableFrom(classType)) tmpCollection = new LinkedHashSet(); else tmpCollection = new Vector(); // get the type of class held in the collection String collectionTypeClassName = null; java.lang.reflect.Type collectionType = ((java.lang.reflect.ParameterizedType) f .getGenericType()).getActualTypeArguments()[0]; if (collectionType.toString().startsWith("class ")) collectionTypeClassName = collectionType.toString().substring("class ".length()); // get the type of class defined in the text node // if it is different, we could be dealing with something like Cohort.memberIds // node type comes through as java.util.Set<classname> String nodeDefinedCollectionType = null; int indexOfLT = nodeDefinedClassName.indexOf("<"); if (indexOfLT > 0) nodeDefinedCollectionType = nodeDefinedClassName.substring(indexOfLT + 1, nodeDefinedClassName.length() - 1); // change the string to just a comma delimited list fieldVal = fieldVal.replaceFirst("\\[", "").replaceFirst("\\]", ""); for (String eachFieldVal : fieldVal.split(",")) { eachFieldVal = eachFieldVal.trim(); // take out whitespace if (!StringUtils.hasText(eachFieldVal)) continue; // try to convert to a simple object Object tmpObject = convertStringToObject(eachFieldVal, (Class) collectionType); // convert to an openmrs object if (tmpObject == null && nodeDefinedCollectionType != null) tmpObject = getOpenmrsObj(nodeDefinedCollectionType, eachFieldVal).getId(); if (tmpObject == null) log.error("Unable to convert: " + eachFieldVal + " to a " + collectionTypeClassName); else tmpCollection.add(tmpObject); } o = tmpCollection; } else if (Map.class.isAssignableFrom(classType) || Properties.class.isAssignableFrom(classType)) { Object tmpMap = SyncUtil.getNormalizer(classType).fromString(classType, fieldVal); //if we were able to convert and got anything at all back, assign it if (tmpMap != null) { o = tmpMap; } } else if ((o = convertStringToObject(fieldVal, classType)) != null) { log.trace("Converted " + fieldVal + " into " + classType.getName()); } else { log.debug("Don't know how to deserialize class: " + className); } } } if (o == null) log.debug("Never found a property named: " + fieldName + " for this class"); return o; }
From source file:org.eclipse.wb.internal.swing.databinding.model.beans.BeanSupport.java
public List<ObserveInfo> createProperties(ObserveInfo parent, IGenericType objectType) { try {/* ww w . j a v a 2 s . c om*/ Class<?> objectClass = objectType.getRawType(); BeanDecorationInfo decorationInfo = DecorationUtils.getDecorationInfo(objectClass); IDecorationProvider decorationProvider = decorationInfo == null ? m_decorationProviderOverType : m_decorationProviderOverInfo; List<ObserveInfo> properties = Lists.newArrayList(); // handle generic TypeVariable<?> superTypeParameter = null; Type superTypeParameterClass = null; if (objectClass.getTypeParameters().length == 1 && objectType.getSubTypes().size() == 1) { superTypeParameter = objectClass.getTypeParameters()[0]; superTypeParameterClass = objectType.getSubTypes().get(0).getRawType(); } else if (objectClass.getGenericSuperclass() instanceof ParameterizedType) { ParameterizedType superType = (ParameterizedType) objectClass.getGenericSuperclass(); if (superType.getActualTypeArguments().length == 1 && superType.getActualTypeArguments()[0] instanceof Class<?> && superType.getRawType() instanceof Class<?>) { Class<?> superClass = (Class<?>) superType.getRawType(); if (superClass.getTypeParameters().length == 1) { superTypeParameter = superClass.getTypeParameters()[0]; superTypeParameterClass = superType.getActualTypeArguments()[0]; } } } // properties for (PropertyDescriptor descriptor : getLocalPropertyDescriptors(objectClass)) { String name = descriptor.getName(); IGenericType propertyType = GenericUtils.getObjectType(superTypeParameter, superTypeParameterClass, descriptor); properties.add(new BeanPropertyObserveInfo(this, parent, name, propertyType, new StringReferenceProvider(name), decorationProvider.getDecorator(decorationInfo, propertyType, name, descriptor))); } // Swing properties if (javax.swing.text.JTextComponent.class.isAssignableFrom(objectClass)) { replaceProperty(properties, "text", new PropertiesObserveInfo(this, parent, "text", ClassGenericType.STRING_CLASS, new StringReferenceProvider("text"), IObserveDecorator.BOLD, new String[] { "text", "text_ON_ACTION_OR_FOCUS_LOST", "text_ON_FOCUS_LOST" })); } else if (javax.swing.JTable.class.isAssignableFrom(objectClass)) { addElementProperties(properties, parent); Collections.sort(properties, ObserveComparator.INSTANCE); } else if (javax.swing.JSlider.class.isAssignableFrom(objectClass)) { replaceProperty(properties, "value", new PropertiesObserveInfo(this, parent, "value", ClassGenericType.INT_CLASS, new StringReferenceProvider("value"), IObserveDecorator.BOLD, new String[] { "value", "value_IGNORE_ADJUSTING" })); } else if (javax.swing.JList.class.isAssignableFrom(objectClass)) { addElementProperties(properties, parent); Collections.sort(properties, ObserveComparator.INSTANCE); } // EL property if (m_addELProperty && !objectClass.isPrimitive()) { properties.add(0, new ElPropertyObserveInfo(parent, objectType)); } // Object property if (m_addSelfProperty && (parent == null || !(parent instanceof BeanPropertyObserveInfo))) { properties.add(0, new ObjectPropertyObserveInfo(objectType)); } // return properties; } catch (Throwable e) { DesignerPlugin.log(e); return Collections.emptyList(); } }
From source file:org.ocelotds.dashboard.services.ServiceToolsTest.java
/** * Test of getTemplateOfParameterizedType method, of class ServiceTools. *///from ww w .j av a2 s .c o m @Test public void testGetTemplateOfParameterizedType() { System.out.println("getTemplateOfParameterizedType"); ParameterizedType parameterizedType = mock(ParameterizedType.class); when(parameterizedType.getRawType()).thenReturn(Collection.class).thenReturn(Map.class) .thenReturn(String.class); doReturn("Iterable").when(instance).getTemplateOfIterable(any(Type[].class), any(IJsonMarshaller.class)); doReturn("Map").when(instance).getTemplateOfMap(any(Type[].class), any(IJsonMarshaller.class)); String result = instance.getTemplateOfParameterizedType(parameterizedType, templateMarshaller); assertThat(result).isEqualTo("Iterable"); result = instance.getTemplateOfParameterizedType(parameterizedType, templateMarshaller); assertThat(result).isEqualTo("Map"); result = instance.getTemplateOfParameterizedType(parameterizedType, templateMarshaller); assertThat(result).isEqualTo("string"); }
From source file:org.openmrs.module.metadatasharing.handler.HandlerEngine.java
/** * Finds a supported type of the given handler * // www . j a v a 2s. c o m * @param handlerType * @param handler * @return the type */ Class<?> findSupportedType(Class<?> handlerType, MetadataHandler<?> handler) { Class<?> supportedType = null; List<Type> types = new ArrayList<Type>(); types.addAll(Arrays.asList(handler.getClass().getGenericInterfaces())); if (handler.getClass().getGenericSuperclass() != null) { types.add(handler.getClass().getGenericSuperclass()); } for (Type type : types) { if (type instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType) type; if (handlerType.isAssignableFrom((Class<?>) parameterizedType.getRawType())) { if (parameterizedType.getActualTypeArguments()[0] instanceof Class) { supportedType = (Class<?>) parameterizedType.getActualTypeArguments()[0]; break; } } } } if (supportedType == null) { throw new IllegalArgumentException(handler.getClass() + " must implement handler interface directly or inherit from a single generic superclass"); } return supportedType; }
From source file:net.firejack.platform.core.utils.Factory.java
public Class getGenericParameterClass(Class actualClass, Class genericClass, int parameterIndex) { if (!genericClass.isAssignableFrom(actualClass) || genericClass.equals(actualClass)) { throw new IllegalArgumentException( "Class " + genericClass.getName() + " is not a superclass of " + actualClass.getName() + "."); }//from ww w. j av a 2 s . co m Stack<ParameterizedType> types = new Stack<ParameterizedType>(); Class clazz = actualClass; while (true) { Type currentType = genericClass.isInterface() ? getGenericInterface(clazz, genericClass) : clazz.getGenericSuperclass(); Type rawType; if (currentType instanceof ParameterizedType) { ParameterizedType type = (ParameterizedType) currentType; types.push(type); rawType = type.getRawType(); } else { types.clear(); rawType = currentType; } if (!rawType.equals(genericClass)) { clazz = (Class) rawType; } else { break; } } if (types.isEmpty()) { return (Class) genericClass.getTypeParameters()[parameterIndex].getGenericDeclaration(); } Type result = types.pop().getActualTypeArguments()[parameterIndex]; while (result instanceof TypeVariable && !types.empty()) { int actualArgumentIndex = getParameterTypeDeclarationIndex((TypeVariable) result); ParameterizedType type = types.pop(); result = type.getActualTypeArguments()[actualArgumentIndex]; } if (result instanceof TypeVariable) { throw new IllegalStateException("Unable to resolve type variable " + result + "." + " Try to replace instances of parametrized class with its non-parameterized subtype."); } if (result instanceof ParameterizedType) { result = ((ParameterizedType) result).getRawType(); } if (result == null) { throw new IllegalStateException( "Unable to determine actual parameter type for " + actualClass.getName() + "."); } if (!(result instanceof Class)) { throw new IllegalStateException( "Actual parameter type for " + actualClass.getName() + " is not a Class."); } return (Class) result; }