List of usage examples for java.lang.reflect ParameterizedType getActualTypeArguments
Type[] getActualTypeArguments();
From source file:springfox.documentation.spring.web.readers.parameter.ExpandedParameterBuilder.java
private Optional<ResolvedType> fieldType(ParameterExpansionContext context) { ParameterizedType parameterized; try {//from w w w .j a v a 2 s . co m if (context.getField().getType().isArray()) { return Optional .<ResolvedType>of(resolver.arrayType(context.getField().getType().getComponentType())); } else { parameterized = (ParameterizedType) context.getField().getGenericType(); Optional<Type> itemClazz = FluentIterable.from(newArrayList(parameterized.getActualTypeArguments())) .first(); if (itemClazz.isPresent()) { return Optional.of(resolver.resolve(context.getField().getType(), itemClazz.get())); } } } catch (Exception e) { LOG.warn("Unable to extract parameterized model attribute"); } return Optional.absent(); }
From source file:org.datalorax.populace.core.util.TypeResolverTest.java
@Test public void shouldNotNeedToWorkAroundApacheCommonsLangTypeUtilsBug() throws Exception { // Given://from ww w .j a va 2s . co m class SomeType { Collection<?> field; } final ParameterizedType wildcardCollectionType = (ParameterizedType) SomeType.class .getDeclaredField("field").getGenericType(); final WildcardType wildcard = (WildcardType) wildcardCollectionType.getActualTypeArguments()[0]; final ParameterizedType ptWithWildcard = org.apache.commons.lang3.reflect.TypeUtils .parameterize(Collection.class, wildcard); final ParameterizedType otherPt = org.apache.commons.lang3.reflect.TypeUtils.parameterize(Collection.class, String.class); // Then: assertThat(otherPt, is(not(equalTo(ptWithWildcard)))); // Passes assertThat(ptWithWildcard, is(equalTo(otherPt))); // should fail! // NB: If this test starts failing at the line above, then the bug in commons.lang has been fixed. // So, remove this test and all the workarounds marked with 'commons.lang bug workaround'. }
From source file:com.mstiles92.plugins.stileslib.config.ConfigObject.java
@SuppressWarnings("rawtypes") protected Class getClassAtDepth(Type type, int depth) throws Exception { if (depth <= 0) { String className = type.toString(); if (className.length() >= 6 && className.substring(0, 6).equalsIgnoreCase("class ")) { className = className.substring(6); }//from www . j av a 2 s . c om if (className.indexOf("<") >= 0) { className = className.substring(0, className.indexOf("<")); } try { return Class.forName(className); } catch (ClassNotFoundException ex) { // ugly fix for primitive data types if (className.equalsIgnoreCase("byte")) return Byte.class; if (className.equalsIgnoreCase("short")) return Short.class; if (className.equalsIgnoreCase("int")) return Integer.class; if (className.equalsIgnoreCase("long")) return Long.class; if (className.equalsIgnoreCase("float")) return Float.class; if (className.equalsIgnoreCase("double")) return Double.class; if (className.equalsIgnoreCase("char")) return Character.class; if (className.equalsIgnoreCase("boolean")) return Boolean.class; throw ex; } } depth--; ParameterizedType pType = (ParameterizedType) type; Type[] typeArgs = pType.getActualTypeArguments(); return getClassAtDepth(typeArgs[typeArgs.length - 1], depth); }
From source file:info.archinnov.achilles.internal.metadata.parsing.PropertyParser.java
public <T> Class<T> inferValueClassForListOrSet(Type genericType, Class<?> entityClass) { log.debug("Infer parameterized value class for collection type {} of entity class {} ", genericType.toString(), entityClass.getCanonicalName()); Class<T> valueClass;/*from w w w. java 2s .co m*/ if (genericType instanceof ParameterizedType) { ParameterizedType pt = (ParameterizedType) genericType; Type[] actualTypeArguments = pt.getActualTypeArguments(); if (actualTypeArguments.length > 0) { Type type = actualTypeArguments[actualTypeArguments.length - 1]; valueClass = getClassFromType(type); } else { throw new AchillesBeanMappingException("The type '" + genericType.getClass().getCanonicalName() + "' of the entity '" + entityClass.getCanonicalName() + "' should be parameterized"); } } else { throw new AchillesBeanMappingException("The type '" + genericType.getClass().getCanonicalName() + "' of the entity '" + entityClass.getCanonicalName() + "' should be parameterized"); } log.trace("Inferred value class : {}", valueClass.getCanonicalName()); return valueClass; }
From source file:info.archinnov.achilles.internal.metadata.parsing.PropertyParser.java
public Class<?> inferEntityClassFromInterceptor(Interceptor<?> interceptor) { for (Type type : interceptor.getClass().getGenericInterfaces()) { if (type instanceof ParameterizedType) { final ParameterizedType parameterizedType = (ParameterizedType) type; Type[] actualTypeArguments = parameterizedType.getActualTypeArguments(); return getClassFromType(actualTypeArguments[0]); }/*from w ww . j av a 2 s . c o m*/ } return null; }
From source file:de.bund.bva.pliscommon.ueberwachung.common.jmx.ServiceStatistikMBean.java
/** * Durchsucht eine Klasse nach Fehlerobjekten, die nicht null sind, oder Fehlercollections, die nicht leer * sind. Fehlerobjekten sind mit {link FachlicherFehler} annotiert. * * Durchsucht Oberklassen & untergeordnete Objektstrukturen ebenfalls rekursiv. * * @param result/*from www .jav a 2 s . c om*/ * Das Objekt * @param clazz * Die Klasse des Objekts durchsucht werden soll (optional). Kann leergelassen werden beim * Start, kann aber genutzt werden um auf Oberklassen eines Objekts zu prfen. * @param tiefe * tiefe Gibt die aktuelle Tiefe des Aufrufs an. Muss erhht werden wenn man die * Klassenstruktur nach unten durchluft. * @return <code>true</code> wenn Fehler gefunden, ansonsten <code>false</code> */ boolean pruefeObjektAufFehler(final Object result, Class<?> clazz, int tiefe) { boolean fehlerGefunden = false; Class<?> clazzToScan = clazz; // Wenn keine Klasse bergeben, selber ermitteln if (clazzToScan == null) { clazzToScan = result.getClass(); } // Wenn max. Tiefe erreicht, nicht weiter prfen if (tiefe > MAXTIEFE) { LOGISY.trace("Max. Tiefe erreicht, prfe nicht weiter auf fachliche Fehler"); return false; } Field[] fields = clazzToScan.getDeclaredFields(); LOGISY.trace("{} Analysiere Objekt {} (Klasse {}) {} Felder gefunden.", StringUtils.repeat("-", tiefe), result.toString(), clazzToScan.getSimpleName(), fields.length); for (Field field : fields) { if (!ClassUtils.isPrimitiveOrWrapper(field.getType()) && !field.getType().isEnum()) { LOGISY.trace("{} {}.{}, Type {}", StringUtils.repeat("-", tiefe), clazzToScan.getSimpleName(), field.getName(), field.getType().getSimpleName()); field.setAccessible(true); try { // Prfe einzelne Klassenfelder (non-Collection) auf annotierten Typ und Vorhandensein if (!Collection.class.isAssignableFrom(field.getType())) { if (field.get(result) != null) { Object fieldObject = field.get(result); if (fieldObject.getClass().isAnnotationPresent(FachlicherFehler.class)) { // Fachliches Fehlerobjekt gefunden return true; } // Wenn kein String, dann prfe rekursiv Objektstruktur if (fieldObject.getClass() != String.class) { fehlerGefunden = pruefeObjektAufFehler(fieldObject, null, tiefe + 1) ? true : fehlerGefunden; } } } else { // Collection, prfen ob fachliche Fehlerliste ParameterizedType type = (ParameterizedType) field.getGenericType(); Class<?> collectionTypeArgument = (Class<?>) type.getActualTypeArguments()[0]; if (collectionTypeArgument.isAnnotationPresent(FachlicherFehler.class)) { // Ist Fehlerliste, prfen ob nicht leer Collection<?> collection = (Collection<?>) field.get(result); if (collection != null && !collection.isEmpty()) { // Fachliche Fehler in Fehlerliste gefunden return true; } } } } catch (IllegalAccessException e) { // Nichts tun, Feld wird ignoriert LOGISY.debug("Feldzugriffsfehler: {}", e.getMessage()); } } } // Die Klassen-Hierachie rekursiv nach oben prfen if (clazzToScan.getSuperclass() != null && !clazzToScan.getSuperclass().equals(Object.class)) { LOGISY.trace("{}> Climb up class hierarchy! Source {}, Target {}", StringUtils.repeat("-", tiefe), clazzToScan.getSimpleName(), clazzToScan.getSuperclass()); fehlerGefunden = // Aufruf mit gleicher Tiefe, da Vererbung nach oben durchlaufen wird pruefeObjektAufFehler(result, clazzToScan.getSuperclass(), tiefe) ? true : fehlerGefunden; } return fehlerGefunden; }
From source file:org.openengsb.core.ekb.common.EDBConverter.java
/** * Loads the generic parameter classes up to the given depth (1 for lists, 2 for maps) *///from ww w . ja va 2 s . com private List<Class<?>> getGenericParameterClasses(Method setterMethod, int depth) { Type t = setterMethod.getGenericParameterTypes()[0]; ParameterizedType pType = (ParameterizedType) t; List<Class<?>> classes = new ArrayList<Class<?>>(); for (int i = 0; i < depth; i++) { classes.add((Class<?>) pType.getActualTypeArguments()[i]); } return classes; }
From source file:org.openmobster.core.mobileObject.xml.MobileObjectSerializer.java
private Object initializeIndexedProperty(Object parentObject, String property, PropertyDescriptor propertyMetaData, List<ArrayMetaData> objectMetaData, String propertyPath) throws Exception { Object element = null;/*from w ww . ja va 2 s .c o m*/ //ArrayUri String arrayUri = null; Integer arrayIndex = 0; if (propertyPath.endsWith("]")) { int lastIndex = propertyPath.lastIndexOf('['); arrayUri = propertyPath.substring(0, lastIndex); arrayIndex = Integer.parseInt(propertyPath.substring(lastIndex + 1, propertyPath.length() - 1).trim()); } ArrayMetaData arrayMetaData = null; for (ArrayMetaData local : objectMetaData) { if (local.arrayUri.equals(arrayUri)) { arrayMetaData = local; break; } } //Find the Class of the elementType String elementTypeName = arrayMetaData.arrayClass; Class elementType = null; if (elementTypeName != null && elementTypeName.trim().length() > 0 && !elementTypeName.equals("null")) { elementType = Thread.currentThread().getContextClassLoader().loadClass(arrayMetaData.arrayClass); } else { //Figure out the element type from the Property Information //This happens when a brand new object is created on the device and is being synced //with the backend //The MobileObject Framework on the device does not know about any Class level information //of the remote bean //The Limitation of this is that: // //* Indexed Properties if Collections must be Parameterized with Concrete Types //* Indexed Properties if Arrays must be Arrays of Concrete Types if (!propertyMetaData.getPropertyType().isArray()) { ParameterizedType returnType = (ParameterizedType) propertyMetaData.getReadMethod() .getGenericReturnType(); Type[] actualTypes = returnType.getActualTypeArguments(); for (Type actualType : actualTypes) { elementType = (Class) actualType; } } else { elementType = propertyMetaData.getPropertyType().getComponentType(); } } //An IndexedProperty Object indexedProperty = PropertyUtils.getProperty(parentObject, propertyMetaData.getName()); //Initialize the IndexedProperty (An Array or Collection) if (propertyMetaData.getPropertyType().isArray()) { int arraySize = arrayMetaData.arrayLength; if (indexedProperty == null) { //Initialize the Array with Size from Object Meta Data PropertyUtils.setProperty(parentObject, propertyMetaData.getName(), Array.newInstance(elementType, arraySize)); } else { //Make sure the Array Size matches int actualSize = Array.getLength(indexedProperty); if (actualSize != arraySize) { //Re-set the existing Array PropertyUtils.setProperty(parentObject, propertyMetaData.getName(), Array.newInstance(elementType, arraySize)); } } } else { if (indexedProperty == null) { //Handle Collection Construction PropertyUtils.setProperty(parentObject, propertyMetaData.getName(), new ArrayList()); } } //Check to see if the index specified by the field requires creation of new //element indexedProperty = PropertyUtils.getProperty(parentObject, propertyMetaData.getName()); if (!propertyMetaData.getPropertyType().isArray()) { try { element = PropertyUtils.getIndexedProperty(parentObject, property); } catch (IndexOutOfBoundsException iae) { Object newlyInitialized = elementType.newInstance(); ((Collection) indexedProperty).add(newlyInitialized); element = newlyInitialized; } } else { element = PropertyUtils.getIndexedProperty(parentObject, property); if (element == null) { Object newlyInitialized = elementType.newInstance(); Array.set(indexedProperty, arrayIndex, newlyInitialized); element = newlyInitialized; } } return element; }
From source file:fr.mby.utils.spring.beans.factory.BasicProxywiredManager.java
/** * Find Bean Type to inject (not the generic type like Collection or Set). * /*from ww w. j av a 2 s .c o m*/ * @param descriptor * @param autowiredBeanNames * @return */ protected Class<?> getBeanType(final DependencyDescriptor descriptor, final Set<String> autowiredBeanNames) { final Class<?> result; Type fieldType = null; final Field field = descriptor.getField(); if (field == null) { // Annotation on the method final MethodParameter methodParameter = descriptor.getMethodParameter(); if (methodParameter != null) { fieldType = methodParameter.getGenericParameterType(); } } else { fieldType = field.getGenericType(); } if (fieldType != null) { final Class<?> type = descriptor.getDependencyType(); if (Collection.class.isAssignableFrom(type)) { final ParameterizedType parameterizedType = (ParameterizedType) fieldType; result = (Class<?>) parameterizedType.getActualTypeArguments()[0]; } else if (Map.class.isAssignableFrom(type)) { final ParameterizedType parameterizedType = (ParameterizedType) fieldType; result = (Class<?>) parameterizedType.getActualTypeArguments()[1]; } else if (type.isArray()) { // We can't do anything throw new IllegalStateException("You cannot use Proxywired annotation on an Array !"); } else { result = type; } } else { throw new IllegalStateException("Unable to find the Bean type !"); } return result; }
From source file:org.apache.ranger.service.RangerBaseModelService.java
@SuppressWarnings("unchecked") public RangerBaseModelService() { Class klass = getClass();/*from w w w . j av a 2 s .c o m*/ ParameterizedType genericSuperclass = (ParameterizedType) klass.getGenericSuperclass(); TypeVariable<Class<?>> var[] = klass.getTypeParameters(); if (genericSuperclass.getActualTypeArguments()[0] instanceof Class) { tEntityClass = (Class<T>) genericSuperclass.getActualTypeArguments()[0]; tViewClass = (Class<V>) genericSuperclass.getActualTypeArguments()[1]; } else if (var.length > 0) { tEntityClass = (Class<T>) var[0].getBounds()[0]; tViewClass = (Class<V>) var[1].getBounds()[0]; } else { LOG.fatal("Cannot find class for template", new Throwable()); } if (tEntityClass != null) { tClassName = tEntityClass.getName(); } populateExistingBaseFields = false; countQueryStr = "SELECT COUNT(obj) FROM " + tClassName + " obj "; queryStr = "SELECT obj FROM " + tClassName + " obj "; }