List of usage examples for org.springframework.util ReflectionUtils doWithFields
public static void doWithFields(Class<?> clazz, FieldCallback fc, @Nullable FieldFilter ff)
From source file:com.logsniffer.util.value.ConfigInjector.java
@Override public Object postProcessBeforeInitialization(final Object bean, final String beanName) throws BeansException { ReflectionUtils.doWithFields(bean.getClass(), new FieldCallback() { @Override/*from w w w . j a v a 2 s . co m*/ public void doWith(final Field field) throws IllegalArgumentException, IllegalAccessException { LOGGER.debug("Injecting value={} for bean={}", field.getName(), beanName); field.setAccessible(true); final String key = field.getAnnotation(Configured.class).value(); final String defaultValue = field.getAnnotation(Configured.class).defaultValue(); final Class<?> targetValueType = (Class<?>) ((ParameterizedType) field.getGenericType()) .getActualTypeArguments()[0]; field.set(bean, new ConfigValue<Object>() { private String oldTextValue; private Object oldValue; @Override public Object get() { String textValue = getSource().getValue(key); if (textValue == null) { textValue = defaultValue; } if (oldTextValue != null && oldTextValue.equals(textValue)) { return oldValue; } else { oldValue = conversionService.convert(textValue, targetValueType); oldTextValue = textValue; return oldValue; } } }); } }, new FieldFilter() { @Override public boolean matches(final Field field) { return field.getType().equals(ConfigValue.class) && field.isAnnotationPresent(Configured.class); } }); return bean; }
From source file:org.web4thejob.orm.AbstractHibernateEntity.java
@SuppressWarnings("CloneDoesntCallSuperClone") @Override// w w w . j a v a2 s . c o m public Entity clone() { try { final Entity clone = (Entity) ReflectHelper.getDefaultConstructor(getClass()) .newInstance((Object[]) null); clone.addDirtyListener(dirtyListener); ReflectionUtils.doWithFields(getClass(), new ReflectionUtils.FieldCallback() { @Override public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException { ReflectionUtils.makeAccessible(field); if (!Collection.class.isAssignableFrom(field.getType())) { // don't clone one-to-many fields field.set(clone, field.get(AbstractHibernateEntity.this)); } } }, ReflectionUtils.COPYABLE_FIELDS); return clone; } catch (Exception e) { e.printStackTrace(); throw new RuntimeException("Clone failed for " + toString(), e); } }
From source file:py.una.pol.karaku.log.LogPostProcessor.java
/** * Revisa todos los mtodos o campos que tengan la anotacin {@link Log} y * le asigna el valor el Log del bean en cuestin. * /* w w w . j a v a 2 s . com*/ * <br /> * * {@inheritDoc} * * @param bean * bean a procesar * @param beanName * nombre del bean * @return el mismo bean * @throws BeansException * nunca */ @Override public Object postProcessBeforeInitialization(final Object bean, final String beanName) { ReflectionUtils.doWithFields(bean.getClass(), new FieldCallback() { @Override public void doWith(Field field) throws IllegalAccessException { if (!Modifier.isFinal(field.getModifiers())) { field.setAccessible(true); Log log = field.getAnnotation(Log.class); field.set(bean, getLogger(bean, log)); } } }, new FieldFilter() { @Override public boolean matches(Field field) { return field.getAnnotation(Log.class) != null; } }); ReflectionUtils.doWithMethods(bean.getClass(), new MethodCallback() { @Override public void doWith(Method method) throws IllegalAccessException { Log log = method.getAnnotation(Log.class); try { method.invoke(bean, getLogger(bean, log)); } catch (InvocationTargetException e) { LOGGER.warn("Error extracting proxy object from {}", bean.getClass().getName(), e); } } }, new MethodFilter() { @Override public boolean matches(Method method) { return method.getAnnotation(Log.class) != null; } }); return bean; }
From source file:org.web4thejob.orm.AbstractHibernateEntity.java
@Override public void merge(final Entity source) { ReflectionUtils.doWithFields(getClass(), new ReflectionUtils.FieldCallback() { @Override/*w ww . ja v a 2s. com*/ public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException { ReflectionUtils.makeAccessible(field); if (!Collection.class.isAssignableFrom(field.getType())) { // don't merge one-to-many fields field.set(AbstractHibernateEntity.this, field.get(source)); } } }, ReflectionUtils.COPYABLE_FIELDS); }
From source file:org.web4thejob.util.L10nUtil.java
public static List<L10nString> getLocalizableResources(final Class<?> localizable) { final List<L10nString> strings = new ArrayList<L10nString>(); final Set<Class> classes = new HashSet<Class>(); classes.add(localizable);//from ww w. j a v a2 s . c om classes.addAll(ClassUtils.getAllInterfacesForClassAsSet(localizable)); for (Class<?> clazz : classes) { ReflectionUtils.doWithFields(clazz, new ReflectionUtils.FieldCallback() { @Override public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException { strings.add((L10nString) field.get(null)); } }, new ReflectionUtils.FieldFilter() { @Override public boolean matches(Field field) { return ReflectionUtils.isPublicStaticFinal(field) && L10nString.class.equals(field.getType()); } }); } //get localizable resources from extension modules for (Module module : ContextUtil.getModules()) { if (module instanceof LocalizableModule) { strings.addAll(((LocalizableModule) module).getLocalizableStrings(classes)); } } // add commands,settings and global strings here... if (DesktopLayoutPanel.class.isAssignableFrom(localizable)) { for (CommandEnum commandEnum : CommandEnum.values()) { L10nString l10nString = new L10nString(CommandEnum.class, commandEnum.name(), L10nUtil.getMessage(commandEnum.getClass(), commandEnum.name(), commandEnum.name())); strings.add(l10nString); } for (SettingEnum settingEnum : SettingEnum.values()) { L10nString l10nString = new L10nString(SettingEnum.class, settingEnum.name(), L10nUtil.getMessage(settingEnum.getClass(), settingEnum.name(), settingEnum.name())); strings.add(l10nString); } for (Condition condition : Condition.getConditions()) { L10nString l10nString = new L10nString(Condition.class, condition.getKey(), condition.getKey()); strings.add(l10nString); } } return strings; }
From source file:py.una.pol.karaku.services.ReflectionConverter.java
/** * // w w w.j a va2 s. c o m * @param source * @param targetClass * @param depth * @param dtoToEntity * @return */ protected Object map(final Object source, final Class<?> targetClass, final int depth, final boolean dtoToEntity) { if (source == null) { return null; } try { final Object toRet = targetClass.newInstance(); ReflectionUtils.doWithFields(source.getClass(), new FieldCallback() { @Override public void doWith(Field field) throws IllegalAccessException { mapField(source, targetClass, depth, dtoToEntity, toRet, field); } }, ReflectionUtils.COPYABLE_FIELDS); return toRet; } catch (Exception e) { throw new KarakuRuntimeException( String.format("Can't copy from %s to %s", source.getClass(), targetClass), e); } }
From source file:com.google.code.simplestuff.bean.BusinessObjectContext.java
/** * Returns an array of all fields used by this object from it's class and * all super classes./*from w w w .j a v a 2s. co m*/ * * @author Andrew Phillips (anph) * @param objectClass the class * @param fields the current field list * @return an array of fields * */ private static Collection<Field> getAnnotatedFields(Class<? extends Object> objectClass) { final List<Field> businessFields = new ArrayList<Field>(); ReflectionUtils.doWithFields(objectClass, new FieldCallback() { // simply add each found field to the list public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException { businessFields.add(field); } }, new FieldFilter() { // match fields with the "@BusinessField" annotation public boolean matches(Field field) { return (field.getAnnotation(BusinessField.class) != null); } }); return businessFields; }
From source file:org.makersoft.activesql.builder.GenericStatementBuilder.java
public GenericStatementBuilder(Configuration configuration, Class<?> entityClass) { super(configuration); this.entityClass = entityClass; String resource = entityClass.getName().replace('.', '/') + ".java (best guess)"; assistant = new MapperBuilderAssistant(configuration, resource); entity = entityClass.getAnnotation(Entity.class); mapperType = entity.mapper();//from w ww.java 2 s.co m if (!mapperType.isAssignableFrom(Void.class)) { namespace = mapperType.getName(); } else { namespace = entityClass.getName(); } assistant.setCurrentNamespace(namespace); databaseId = super.getConfiguration().getDatabaseId(); lang = super.getConfiguration().getDefaultScriptingLanuageInstance(); //~~~~~~~~~~~~~~~~~~~~~~~~~~~ Table table = entityClass.getAnnotation(Table.class); if (table == null) { tableName = CaseFormatUtils.camelToUnderScore(entityClass.getSimpleName()); } else { tableName = table.name(); } ///~~~~~~~~~~~~~~~~~~~~~~ idField = AnnotationUtils.findDeclaredFieldWithAnnoation(Id.class, entityClass); versionField = AnnotationUtils.findDeclaredFieldWithAnnoation(Version.class, entityClass); ReflectionUtils.doWithFields(entityClass, new FieldCallback() { @Override public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException { columnFields.add(field); } }, new FieldFilter() { @Override public boolean matches(Field field) { if (Modifier.isStatic(field.getModifiers()) || Modifier.isFinal(field.getModifiers())) { return false; } for (Annotation annotation : field.getAnnotations()) { if (Transient.class.isAssignableFrom(annotation.getClass()) || Id.class.isAssignableFrom(annotation.getClass())) { return false; } } return true; } }); }
From source file:py.una.pol.karaku.test.util.TestUtils.java
private static Set<Class<?>> getReferencedClasses(Class<?> base, final Set<Class<?>> elements) { ReflectionUtils.doWithFields(base, new FieldCallback() { @Override/*from www .ja v a2 s.c o m*/ public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException { if (elements.add(getType(field))) { getReferencedClasses(getType(field), elements); } } }, new FieldFilter() { @Override public boolean matches(Field field) { return AnnotationUtils.findAnnotation(getType(field), Entity.class) != null; } }); return elements; }
From source file:org.javelin.sws.ext.bind.internal.metadata.PropertyCallback.java
/** * <p>Reads class' metadata and returns a {@link XmlEventsPattern pattern of XML events} which may be used to marshal * an object of the analyzed class.<?p> * // w w w. j av a2 s .c o m * @return */ public TypedPattern<T> analyze() { TypedPattern<T> result = this.patternRegistry.findPatternByClass(this.clazz); if (result != null) return result; log.trace("Analyzing {} class with {} type name", this.clazz.getName(), this.typeName); // analyze fields ReflectionUtils.doWithFields(this.clazz, this, new FieldFilter() { @Override public boolean matches(Field field) { return !Modifier.isStatic(field.getModifiers()); } }); // analyze get/set methods - even private ones! ReflectionUtils.doWithMethods(this.clazz, this, new MethodFilter() { @Override public boolean matches(Method method) { boolean match = true; // is it getter? match &= method.getName().startsWith("get"); match &= method.getParameterTypes().length == 0; match &= method.getReturnType() != Void.class; // is there a setter? if (match) { Method setter = ReflectionUtils.findMethod(clazz, method.getName().replaceFirst("^get", "set"), method.getReturnType()); // TODO: maybe allow non-void returning setters as Spring-Framework already does? Now: yes match = setter != null || Collection.class.isAssignableFrom(method.getReturnType()); } return match; } }); if (this.valueMetadata != null && this.childElementMetadata.size() == 0 && this.childAttributeMetadata.size() == 0) { // we have a special case, where Java class becomes simpleType: // - formatting the analyzed class is really formatting the value // - the type information of the analyzed class is not changed! log.trace("Changing {} class' pattern to SimpleContentPattern", this.clazz.getName()); SimpleContentPattern<T> valuePattern = SimpleContentPattern.newValuePattern(this.typeName, this.clazz); SimpleContentPattern<?> simpleTypePattern = (SimpleContentPattern<?>) this.valueMetadata.getPattern(); valuePattern.setFormatter( PeelingFormatter.newPeelingFormatter(this.valueMetadata, simpleTypePattern.getFormatter())); result = valuePattern; } else { if (this.valueMetadata != null && this.childElementMetadata.size() > 0) { throw new RuntimeException("TODO: can't mix @XmlValue and @XmlElements"); } // we have complex type (possibly with simpleContent, when there's @XmlValue + one or more @XmlAttributes) // @XmlAttributes first. then @XmlElements this.childAttributeMetadata.addAll(this.childElementMetadata); if (this.valueMetadata != null) this.childAttributeMetadata.add(this.valueMetadata); result = ComplexTypePattern.newContentModelPattern(this.typeName, this.clazz, this.childAttributeMetadata); } if (log.isTraceEnabled()) log.trace("-> Class {} was mapped to {} with {} XSD type", this.clazz.getName(), result, this.typeName); return result; }