List of usage examples for java.lang.reflect Field getGenericType
public Type getGenericType()
From source file:io.neba.core.resourcemodels.metadata.MappedFieldMetaData.java
/** * Immediately extracts all metadata for the provided field. * * @param field must not be <code>null</code>. *//* w w w . j av a 2 s .co m*/ public MappedFieldMetaData(Field field, Class<?> modelType) { if (field == null) { throw new IllegalArgumentException("Constructor parameter field must not be null."); } if (modelType == null) { throw new IllegalArgumentException("Method argument modelType must not be null."); } // Atomic initialization this.modelType = modelType; this.field = field; this.isLazy = field.getType() == Lazy.class; this.annotations = annotations(field); // Treat Optional<X> fields transparently like X fields: This way, anyone operating on the metadata is not // forced to be aware of the lazy-loading value holder indirection but can operate on the target type directly. this.genericFieldType = this.isLazy ? getParameterTypeOf(field.getGenericType()) : field.getGenericType(); this.fieldType = this.isLazy ? getRawType(this.genericFieldType, this.modelType) : field.getType(); this.isCollectionType = Collection.class.isAssignableFrom(this.fieldType); this.isPathAnnotationPresent = this.annotations.contains(Path.class); this.isReference = this.annotations.contains(Reference.class); this.isThisReference = this.annotations.contains(This.class); this.isChildrenAnnotationPresent = this.annotations.contains(Children.class); // The following initializations are not atomic but order-sensitive. this.isAppendPathPresentOnReference = isAppendPathPresentOnReferenceInternal(); this.appendPathOnReference = getAppendPathFromReference(); this.isResolveBelowEveryChildPathPresentOnChildren = isResolveBelowEveryChildPathPresentOnChildrenInternal(); this.resolveBelowEveryChildPathOnChildren = getResolveBelowEveryChildPathFromChildren(); this.typeParameter = resolveTypeParameter(); this.arrayTypeOfComponentType = resolveArrayTypeOfComponentType(); this.path = getPathInternal(); this.isPropertyType = isPropertyTypeInternal(); this.isInstantiableCollectionType = ReflectionUtil.isInstantiableCollectionType(this.fieldType); enforceInstantiableCollectionTypeForExplicitlyMappedFields(); this.collectionProxyFactory = prepareProxyFactoryForCollectionTypes(); makeAccessible(field); }
From source file:org.jbpm.formModeler.core.model.PojoDataHolder.java
private Set<DataFieldHolder> calculatePropertyNames() throws Exception { Class clazz = getHolderClass(); if (clazz == null) { return null; }/*from w ww . j a va 2s. com*/ Set<DataFieldHolder> dataFieldHolders = new TreeSet<DataFieldHolder>(); for (Field field : clazz.getDeclaredFields()) { if (isValidType(field.getType().getName())) { String capitalizedName = capitalize(field.getName()); try { Method setter = clazz.getDeclaredMethod("set" + capitalizedName, field.getType()); if (!setter.getReturnType().getName().equals("void") && !Modifier.isPublic(setter.getModifiers())) continue; Method getter; if (field.getType().equals(boolean.class)) getter = clazz.getDeclaredMethod("is" + capitalizedName); else getter = clazz.getDeclaredMethod("get" + capitalizedName); if (!getter.getReturnType().equals(field.getType()) && !Modifier.isPublic(getter.getModifiers())) continue; Type type = field.getGenericType(); DataFieldHolder fieldHolder; if (type instanceof ParameterizedType) { ParameterizedType generictype = (ParameterizedType) type; Type[] arguments = generictype.getActualTypeArguments(); if (arguments == null || arguments.length > 1) fieldHolder = new DataFieldHolder(this, field.getName(), field.getType().getName()); else fieldHolder = new DataFieldHolder(this, field.getName(), field.getType().getName(), ((Class<?>) arguments[0]).getName()); } else { fieldHolder = new DataFieldHolder(this, field.getName(), field.getType().getName()); } dataFieldHolders.add(fieldHolder); } catch (Exception e) { getLogger().debug("Unable to generate field holder for '{}': {}", field.getName(), e); } } } return dataFieldHolders; }
From source file:richtercloud.reflection.form.builder.fieldhandler.MappingFieldHandler.java
/** * Must never return {@code null}, otherwise {@link #handle(java.lang.reflect.Field, java.lang.Object, richtercloud.reflection.form.builder.fieldhandler.FieldUpdateListener, richtercloud.reflection.form.builder.ReflectionFormBuilder) } throws {@link IllegalArgumentException}. * @param field/*www . j ava2 s . c om*/ * @param instance * @param updateListener * @param reflectionFormBuilder * @return * @throws IllegalArgumentException * @throws IllegalAccessException * @throws FieldHandlingException * @throws InvocationTargetException * @throws NoSuchMethodException * @throws InstantiationException */ protected Pair<JComponent, ComponentHandler<?>> handle0(final Field field, final Object instance, FieldUpdateListener<E> updateListener, R reflectionFormBuilder) throws IllegalArgumentException, IllegalAccessException, FieldHandlingException, InvocationTargetException, NoSuchMethodException, InstantiationException { JComponent retValue; T fieldValue = (T) field.get(instance); String fieldName = field.getName(); Class<?> declaringClass = field.getDeclaringClass(); FieldHandler fieldHandler = null; //can't have a generic type because it requires R to be passed down //the call hierarchy which requires to redesign the whole mapping //factory hierarchy which is extremely difficult due to entangled //generics like FieldHandler<T, FieldUpdateEvent<T>, ...> if (field.getType().isPrimitive()) { fieldHandler = primitiveMapping.get(field.getType()); } else { // check exact type match fieldHandler = retrieveFieldHandler(field.getGenericType(), classMapping); } ComponentHandler<?> componentResettable; if (fieldHandler == null) { return null; } retValue = fieldHandler.handle(field, instance, new FieldUpdateListener<FieldUpdateEvent<?>>() { @Override public void onUpdate(FieldUpdateEvent<?> event) { try { field.set(instance, event.getNewValue()); } catch (IllegalArgumentException | IllegalAccessException ex) { throw new RuntimeException(ex); } } }, reflectionFormBuilder); componentResettable = fieldHandler; return new ImmutablePair<JComponent, ComponentHandler<?>>(retValue, componentResettable); }
From source file:com.qihang.winter.poi.excel.export.base.ExportBase.java
/** * ??//w w w. ja v a 2s . c om * * @param exclusions * @param targetId * ID * @param fields * @throws Exception */ public void getAllExcelField(String[] exclusions, String targetId, Field[] fields, List<com.qihang.winter.poi.excel.entity.params.ExcelExportEntity> excelParams, Class<?> pojoClass, List<Method> getMethods) throws Exception { List<String> exclusionsList = exclusions != null ? Arrays.asList(exclusions) : null; com.qihang.winter.poi.excel.entity.params.ExcelExportEntity excelEntity; // ??filed for (int i = 0; i < fields.length; i++) { Field field = fields[i]; // ?collection,?java,? if (com.qihang.winter.poi.util.PoiPublicUtil.isNotUserExcelUserThis(exclusionsList, field, targetId)) { continue; } // Excel ??? if (field.getAnnotation(com.qihang.winter.poi.excel.annotation.Excel.class) != null) { excelParams.add(createExcelExportEntity(field, targetId, pojoClass, getMethods)); } else if (com.qihang.winter.poi.util.PoiPublicUtil.isCollection(field.getType())) { com.qihang.winter.poi.excel.annotation.ExcelCollection excel = field .getAnnotation(com.qihang.winter.poi.excel.annotation.ExcelCollection.class); ParameterizedType pt = (ParameterizedType) field.getGenericType(); Class<?> clz = (Class<?>) pt.getActualTypeArguments()[0]; List<com.qihang.winter.poi.excel.entity.params.ExcelExportEntity> list = new ArrayList<com.qihang.winter.poi.excel.entity.params.ExcelExportEntity>(); getAllExcelField(exclusions, StringUtils.isNotEmpty(excel.id()) ? excel.id() : targetId, com.qihang.winter.poi.util.PoiPublicUtil.getClassFields(clz), list, clz, null); excelEntity = new com.qihang.winter.poi.excel.entity.params.ExcelExportEntity(); excelEntity.setName(getExcelName(excel.name(), targetId)); excelEntity.setOrderNum(getCellOrder(excel.orderNum(), targetId)); excelEntity .setMethod(com.qihang.winter.poi.util.PoiPublicUtil.getMethod(field.getName(), pojoClass)); excelEntity.setList(list); excelParams.add(excelEntity); } else { List<Method> newMethods = new ArrayList<Method>(); if (getMethods != null) { newMethods.addAll(getMethods); } newMethods.add(com.qihang.winter.poi.util.PoiPublicUtil.getMethod(field.getName(), pojoClass)); com.qihang.winter.poi.excel.annotation.ExcelEntity excel = field .getAnnotation(com.qihang.winter.poi.excel.annotation.ExcelEntity.class); getAllExcelField(exclusions, StringUtils.isNotEmpty(excel.id()) ? excel.id() : targetId, com.qihang.winter.poi.util.PoiPublicUtil.getClassFields(field.getType()), excelParams, field.getType(), newMethods); } } }
From source file:fr.juanwolf.mysqlbinlogreplicator.component.DomainClassAnalyzer.java
@PostConstruct public void postConstruct() throws BeansException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException { mappingTablesExpected = new ArrayList<>(); nestedTables = new ArrayList<>(); Reflections reflections = new Reflections(scanMapping); Set<Class<?>> types = reflections.getTypesAnnotatedWith(MysqlMapping.class); final Iterator<Class<?>> iterator = types.iterator(); while (iterator.hasNext()) { Class classDomain = iterator.next(); MysqlMapping mysqlMapping = (MysqlMapping) classDomain.getAnnotation(MysqlMapping.class); DomainClass domainClass = new DomainClass(); domainClass.setDomainClass(classDomain); mappingTablesExpected.add(mysqlMapping.table()); CrudRepository crudRepository = (CrudRepository) applicationContext.getBean(mysqlMapping.repository()); domainClass.setCrudRepository(crudRepository); domainClass.setTable(mysqlMapping.table()); Map<String, SQLRequester> nestedClassesMap = new HashMap<>(); for (Field field : classDomain.getDeclaredFields()) { NestedMapping nestedMapping = field.getAnnotation(NestedMapping.class); if (nestedMapping != null) { Class sqlRequesterClass = nestedMapping.sqlAssociaton().getRequesterClass(); Constructor sqlRequesterConstructor = sqlRequesterClass.getConstructor(); SQLRequester sqlRequester = (SQLRequester) sqlRequesterConstructor.newInstance(); sqlRequester.setDatabaseName(databaseName); sqlRequester.setEntryTableName(mysqlMapping.table()); sqlRequester.setExitTableName(nestedMapping.table()); sqlRequester.setForeignKey(nestedMapping.foreignKey()); sqlRequester.setPrimaryKeyForeignEntity(nestedMapping.primaryKey()); sqlRequester.setEntryType(classDomain); sqlRequester.setAssociatedField(field); Class foreignType = field.getType(); if (field.getGenericType() instanceof ParameterizedType) { ParameterizedType genericType = (ParameterizedType) field.getGenericType(); Class properType = (Class) genericType.getActualTypeArguments()[0]; foreignType = properType; }/* w ww .j av a 2 s . c o m*/ sqlRequester.setForeignType(foreignType); sqlRequester.setJdbcTemplate(jdbcTemplate); NestedRowMapper currentClassNestedRowMapper = new NestedRowMapper(classDomain, this, mysqlMapping.table()); NestedRowMapper foreignClassNestedRowMapper = new NestedRowMapper(foreignType, this, mysqlMapping.table()); sqlRequester.setRowMapper(currentClassNestedRowMapper); sqlRequester.setForeignRowMapper(foreignClassNestedRowMapper); nestedClassesMap.put(field.getName(), sqlRequester); nestedTables.add(nestedMapping.table()); nestedDomainClassMap.put(nestedMapping.table(), domainClass); } } domainClass.setSqlRequesters(nestedClassesMap); domainClassMap.put(domainClass.getTable(), domainClass); } if (environment.getProperty("date.output") != null) { binlogOutputDateFormatter = new SimpleDateFormat(environment.getProperty("date.output")); } }
From source file:py.una.pol.karaku.reports.DynamicUtils.java
/** * Metodo que obtiene la clase de cada detalle que sera incorporado en los * reportes del tipo cabecera-detalle.//from ww w .ja v a 2 s. c o m * * @param clazz * Clase de la cabecera * @param detail * Detalle que se desea agregar al reporte * @return Clase del detalle * @throws ReportException */ private Class<?> getClazzDetail(Class<?> clazz, Detail detail) throws ReportException { Class<?> clazzDetail = null; try { if (detail.getField().contains(".")) { clazzDetail = Object.class; } else { Field field = clazz.getDeclaredField(detail.getField()); clazzDetail = (Class<?>) ((ParameterizedType) field.getGenericType()).getActualTypeArguments()[0]; } } catch (NoSuchFieldException e) { throw new ReportException(e); } return clazzDetail; }
From source file:org.compass.annotations.config.binding.AnnotationsMappingBinding.java
/** * Recursivly process the class to find all it's annotations. Lower level * class/interfaces with annotations will be added first. *///from w w w .j a va2 s.c o m private void processAnnotatedClass(Class<?> clazz) { if (clazz.equals(Class.class)) { return; } Class<?> superClazz = clazz.getSuperclass(); if (superClazz != null && !superClazz.equals(Object.class)) { processAnnotatedClass(superClazz); } Class<?>[] interfaces = clazz.getInterfaces(); for (Class<?> anInterface : interfaces) { processAnnotatedClass(anInterface); } SearchableConstant searchableConstant = clazz.getAnnotation(SearchableConstant.class); if (searchableConstant != null) { bindConstantMetaData(searchableConstant); } SearchableConstants searchableConstants = clazz.getAnnotation(SearchableConstants.class); if (searchableConstants != null) { for (SearchableConstant metaData : searchableConstants.value()) { bindConstantMetaData(metaData); } } SearchableDynamicMetaData searchableDynamicMetaData = clazz.getAnnotation(SearchableDynamicMetaData.class); if (searchableDynamicMetaData != null) { bindDynamicMetaData(searchableDynamicMetaData); } SearchableDynamicMetaDatas searchableDynamicMetaDatas = clazz .getAnnotation(SearchableDynamicMetaDatas.class); if (searchableDynamicMetaDatas != null) { for (SearchableDynamicMetaData metaData : searchableDynamicMetaDatas.value()) { bindDynamicMetaData(metaData); } } // handles recursive extends and the original extend if (clazz.isAnnotationPresent(Searchable.class)) { Searchable searchable = clazz.getAnnotation(Searchable.class); String[] extend = searchable.extend(); if (extend.length != 0) { ArrayList<String> extendedMappings = new ArrayList<String>(); if (classMapping.getExtendedAliases() != null) { extendedMappings.addAll(Arrays.asList(classMapping.getExtendedAliases())); } for (String extendedAlias : extend) { Alias extendedAliasLookup = valueLookup.lookupAlias(extendedAlias); if (extendedAliasLookup == null) { extendedMappings.add(extendedAlias); } else { extendedMappings.add(extendedAliasLookup.getName()); } } classMapping.setExtendedAliases(extendedMappings.toArray(new String[extendedMappings.size()])); } } // if the super class has Searchable annotation as well, add it to the list of extends ArrayList<Class> extendedClasses = new ArrayList<Class>(); if (clazz.getSuperclass() != null) { extendedClasses.add(clazz.getSuperclass()); } extendedClasses.addAll(Arrays.asList(clazz.getInterfaces())); for (Class<?> superClass : extendedClasses) { if (!superClass.isAnnotationPresent(Searchable.class)) { continue; } Searchable superSearchable = superClass.getAnnotation(Searchable.class); String alias = getAliasFromSearchableClass(superClass, superSearchable); HashSet<String> extendedMappings = new HashSet<String>(); if (classMapping.getExtendedAliases() != null) { extendedMappings.addAll(Arrays.asList(classMapping.getExtendedAliases())); } extendedMappings.add(alias); classMapping.setExtendedAliases(extendedMappings.toArray(new String[extendedMappings.size()])); } for (Field field : clazz.getDeclaredFields()) { for (Annotation annotation : field.getAnnotations()) { processsAnnotatedElement(clazz, field.getName(), "field", field.getType(), field.getGenericType(), annotation, field); } } for (Method method : clazz.getDeclaredMethods()) { if (!method.isSynthetic() && !method.isBridge() && !Modifier.isStatic(method.getModifiers()) && method.getParameterTypes().length == 0 && method.getReturnType() != void.class && (method.getName().startsWith("get") || method.getName().startsWith("is"))) { for (Annotation annotation : method.getAnnotations()) { processsAnnotatedElement(clazz, ClassUtils.getShortNameForMethod(method), "property", method.getReturnType(), method.getGenericReturnType(), annotation, method); } } } }
From source file:org.tdar.core.service.ReflectionService.java
/** * Find all beans that implment the @link Persistable interface * //from w ww. j av a2 s . co m * @param cls * @return */ @SuppressWarnings("unchecked") public List<Pair<Field, Class<? extends Persistable>>> findAllPersistableFields(Class<?> cls) { List<Field> declaredFields = new ArrayList<>(); List<Pair<Field, Class<? extends Persistable>>> result = new ArrayList<>(); // iterate up the package hierarchy while (cls.getPackage().getName().startsWith(ORG_TDAR)) { CollectionUtils.addAll(declaredFields, cls.getDeclaredFields()); cls = cls.getSuperclass(); } for (Field field : declaredFields) { Class<? extends Persistable> type = null; // generic collections if (java.lang.reflect.Modifier.isStatic(field.getModifiers()) || java.lang.reflect.Modifier.isTransient(field.getModifiers()) || java.lang.reflect.Modifier.isFinal(field.getModifiers())) { continue; } if (Collection.class.isAssignableFrom(field.getType())) { ParameterizedType stringListType = (ParameterizedType) field.getGenericType(); if (Persistable.class.isAssignableFrom( (Class<? extends Persistable>) stringListType.getActualTypeArguments()[0])) { type = (Class<? extends Persistable>) stringListType.getActualTypeArguments()[0]; logger.trace("\t -> {}", type); // class java.lang.String. } } // singletons if (Persistable.class.isAssignableFrom(field.getType())) { type = (Class<? extends Persistable>) field.getType(); logger.trace("\t -> {}", type); // class java.lang.String. } // things to add if (type != null) { result.add(new Pair<Field, Class<? extends Persistable>>(field, type)); } } return result; }