List of usage examples for org.springframework.util ReflectionUtils setField
public static void setField(Field field, @Nullable Object target, @Nullable Object value)
From source file:kelly.core.injector.AbstractSpringInjector.java
@Override public final void inject(Object bean) { if (bean == null) return;/*from ww w.j a va2s . c o m*/ Field[] fields = getFieldsIncludingSuperclass(bean); for (Field field : fields) { Inject inject = field.getAnnotation(Inject.class); boolean nullable = field.getAnnotation(Nullable.class) != null; if (inject == null) { continue; } else { String beanName = inject.value(); Object com = null; if ("".equals(beanName)) { // com = getBeanFromApplicationContext(field.getType()); } else { com = getBeanFromApplicationContext(beanName); } if (com == null) { if (nullable) { continue; } else { throw new InjectException("Inject failed for field " + field.toString()); } } ReflectionUtils.makeAccessible(field); ReflectionUtils.setField(field, bean, com); } } }
From source file:com.ryantenney.metrics.spring.MetricAnnotationBeanPostProcessor.java
@Override protected void withField(Object bean, String beanName, Class<?> targetClass, Field field) { final Metric annotation = field.getAnnotation(Metric.class); final String metricName = Util.forMetricField(targetClass, field, annotation); final Class<?> type = field.getType(); if (!com.codahale.metrics.Metric.class.isAssignableFrom(type)) { throw new IllegalArgumentException("Field " + targetClass.getCanonicalName() + "." + field.getName() + " must be a subtype of " + com.codahale.metrics.Metric.class.getCanonicalName()); }//from w w w . j a v a2s. c o m ReflectionUtils.makeAccessible(field); // Get the value of the field annotated with @Metric com.codahale.metrics.Metric metric = (com.codahale.metrics.Metric) ReflectionUtils.getField(field, bean); if (metric == null) { // If null, create a metric of the appropriate type and inject it metric = getMetric(metrics, type, metricName); ReflectionUtils.setField(field, bean, metric); LOG.debug("Injected metric {} for field {}.{}", metricName, targetClass.getCanonicalName(), field.getName()); } else { // If non-null, register that instance of the metric try { // Attempt to register that instance of the metric metrics.register(metricName, metric); LOG.debug("Registered metric {} for field {}.{}", metricName, targetClass.getCanonicalName(), field.getName()); } catch (IllegalArgumentException ex1) { // A metric is already registered under that name // (Cannot determine the cause without parsing the Exception's message) try { metric = getMetric(metrics, type, metricName); ReflectionUtils.setField(field, bean, metric); LOG.debug("Injected metric {} for field {}.{}", metricName, targetClass.getCanonicalName(), field.getName()); } catch (IllegalArgumentException ex2) { // A metric of a different type is already registered under that name throw new IllegalArgumentException("Error injecting metric for field " + targetClass.getCanonicalName() + "." + field.getName(), ex2); } } } }
From source file:py.una.pol.karaku.dao.entity.interceptors.TimeInterceptor.java
@Override public void intercept(Operation op, Field f, Object bean) { Object o = ReflectionUtils.getField(f, bean); if (o == null) { return;/* ww w.ja v a 2s . co m*/ } Time t = f.getAnnotation(Time.class); Date date = (Date) o; Calendar c = Calendar.getInstance(); c.setTime(date); if ((t == null) || t.type().equals(Time.Type.DATE)) { this.handleDate(c); } else if (t.type().equals(Time.Type.TIME)) { this.handleTime(c); } // DATETIME no es manejado por que no requeire ningun // trato especial c.set(Calendar.SECOND, 0); c.set(Calendar.MILLISECOND, 0); ReflectionUtils.setField(f, bean, c.getTime()); }
From source file:com.ciphertool.genetics.algorithms.mutation.GroupMutationAlgorithmTest.java
@BeforeClass public static void setUp() throws IllegalArgumentException, IllegalAccessException { Field maxGenesPerGroupField = ReflectionUtils.findField(GroupMutationAlgorithm.class, "MAX_GENES_PER_GROUP"); ReflectionUtils.makeAccessible(maxGenesPerGroupField); ReflectionUtils.setField(maxGenesPerGroupField, null, 2); groupMutationAlgorithm = new GroupMutationAlgorithm(); geneDaoMock = mock(VariableLengthGeneDao.class); groupMutationAlgorithm.setGeneDao(geneDaoMock); logMock = mock(Logger.class); Field logField = ReflectionUtils.findField(GroupMutationAlgorithm.class, "log"); ReflectionUtils.makeAccessible(logField); ReflectionUtils.setField(logField, groupMutationAlgorithm, logMock); }
From source file:com.ebiz.modules.persistence.repository.support.MyRepositoryImpl.java
@Override @Transactional/* ww w.j ava 2s .c om*/ public void delete(T entity) { logger.trace("----->MyRepositoryImpl.delete(T entity)"); Assert.notNull(entity, "The entity must not be null!"); Class<?> clazz = entity.getClass(); if (clazz.isAnnotationPresent(LogicallyDelete.class)) { LogicallyDelete logicallyDelete = clazz.getAnnotation(LogicallyDelete.class); Object value = ConvertUtils.convert(logicallyDelete.value(), logicallyDelete.type().getClazz()); Field field = ReflectionUtils.findField(entity.getClass(), logicallyDelete.name()); ReflectionUtils.makeAccessible(field); ReflectionUtils.setField(field, entity, value); save(entity); } else { super.delete(entity); } }
From source file:py.una.pol.karaku.dao.entity.interceptors.UriInterceptor.java
@Override public void intercept(Operation op, Field field, Object bean) { URI uri = notNull(field.getAnnotation(URI.class), "Intercept a field without uri in UriInterceptor"); String baseUri = Validate.notNull(uri.baseUri(), "Base uri in a @URI is null or empty"); String finalUri = null;//from w w w . ja v a 2 s .c om switch (uri.type()) { case FIELD: finalUri = byUniqueField(field, bean, uri); break; case SEQUENCE: finalUri = bySequence(field, uri); break; default: throw new IllegalArgumentException(); } ReflectionUtils.setField(field, bean, baseUri + finalUri); }
From source file:py.una.pol.karaku.dao.entity.interceptors.CaseSensitiveInterceptor.java
@Override public void intercept(Operation op, Field f, Object bean) { Object o = ReflectionUtils.getField(f, bean); String s = (String) o; if (s != null) { s = s.toUpperCase();//from w w w.ja v a 2 s.c o m ReflectionUtils.setField(f, bean, s); } }
From source file:com.ciphertool.genetics.algorithms.mutation.LiberalMutationAlgorithmTest.java
@BeforeClass public static void setUp() { liberalMutationAlgorithm = new LiberalMutationAlgorithm(); geneDaoMock = mock(VariableLengthGeneDao.class); liberalMutationAlgorithm.setGeneDao(geneDaoMock); chromosomeHelperSpy = spy(new KeylessChromosomeHelper()); geneDaoMockForChromosomeHelper = mock(VariableLengthGeneDao.class); liberalMutationAlgorithm.setChromosomeHelper(chromosomeHelperSpy); logMock = mock(Logger.class); Field logField = ReflectionUtils.findField(LiberalMutationAlgorithm.class, "log"); ReflectionUtils.makeAccessible(logField); ReflectionUtils.setField(logField, liberalMutationAlgorithm, logMock); }
From source file:org.kaleidofoundry.spring.context.BeanContextPostProcessor.java
@Override public Object postProcessBeforeInitialization(final Object beanInstance, final String beanName) throws BeansException { Set<Field> fields = ReflectionHelper.getAllDeclaredFields(beanInstance.getClass()); for (Field field : fields) { // @Autowired is injected using spring bean if (field.isAnnotationPresent(Context.class) && !field.isAnnotationPresent(Autowired.class) && !field.isAnnotationPresent(Inject.class)) { final Context context = field.getAnnotation(Context.class); // do field is a runtime context class if (field.getType().isAssignableFrom(RuntimeContext.class)) { ReflectionUtils.makeAccessible(field); ReflectionUtils.setField(field, beanInstance, RuntimeContext.createFrom(context, field.getName(), field.getDeclaringClass())); }//from w ww.j av a 2 s.c o m // does the plugin interface have a provider specify else if (field.getType().isAnnotationPresent(Provider.class)) { try { ReflectionUtils.makeAccessible(field); Object fieldValue = field.get(beanInstance); if (fieldValue == null) { // create provider using annotation meta-information final Provider provideInfo = field.getType().getAnnotation(Provider.class); final Constructor<? extends ProviderService<?>> providerConstructor = provideInfo .value().getConstructor(Class.class); final ProviderService<?> fieldProviderInstance = providerConstructor .newInstance(field.getType()); // invoke provides method with Context annotation meta-informations final Method providesMethod = ReflectionUtils.findMethod(provideInfo.value(), ProviderService.PROVIDES_METHOD, Context.class, String.class, Class.class); // get the provider result fieldValue = ReflectionUtils.invokeMethod(providesMethod, fieldProviderInstance, context, field.getName(), field.getType()); // set the field that was not yet injected ReflectionUtils.setField(field, beanInstance, fieldValue); } } catch (IllegalArgumentException e) { throw new BeanCreationException("Unexpected error during injection", e); } catch (IllegalAccessException e) { throw new BeanCreationException("Unexpected error during injection", e); } catch (SecurityException e) { throw new BeanCreationException("Unexpected error during injection", e); } catch (NoSuchMethodException e) { throw new BeanCreationException("Unexpected error during injection", e); } catch (InstantiationException e) { throw new BeanCreationException("Unexpected error during injection", e); } catch (InvocationTargetException ite) { throw new BeanCreationException("", ite.getCause() != null ? ite.getCause() : (ite.getTargetException() != null ? ite.getTargetException() : ite)); } finally { } } } } return beanInstance; }
From source file:com.excilys.ebi.utils.spring.log.slf4j.InjectLoggerAnnotationBeanPostProcessor.java
/** * Processes a bean's fields for injection if it has a {@link InjectLogger} * annotation./*from w w w. jav a 2 s . co m*/ */ protected void processLogger(final Object bean) { final Class<?> clazz = bean.getClass(); ReflectionUtils.doWithFields(clazz, new FieldCallback() { public void doWith(Field field) { Annotation annotation = field.getAnnotation(InjectLogger.class); if (annotation != null) { int modifiers = field.getModifiers(); Assert.isTrue(!Modifier.isStatic(modifiers), "InjectLogger annotation is not supported on static fields"); Assert.isTrue(!Modifier.isFinal(modifiers), "InjectLogger annotation is not supported on final fields"); ReflectionUtils.makeAccessible(field); Logger logger = LoggerFactory.getLogger(clazz); ReflectionUtils.setField(field, bean, logger); } } }); }