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.consol.citrus.admin.mock.Mocks.java
/** * Inject Spring autowired fields in target instance with mocks. * @param target//ww w.j a v a2 s .c o m */ public static void injectMocks(Object target) { ReflectionUtils.doWithFields(target.getClass(), field -> ReflectionUtils.setField(field, target, Mockito.mock(field.getType())), field -> { if (field.isAnnotationPresent(Autowired.class)) { if (!field.isAccessible()) { ReflectionUtils.makeAccessible(field); } return true; } return false; }); }
From source file:org.dkpro.lab.task.impl.ParameterUtil.java
public static List<String> findBeanPropertiesWithName(Object aObject, String aName) { List<String> beanProperties = new ArrayList<>(); ReflectionUtils.doWithFields(aObject.getClass(), f -> { if (aName.equals(getName(f.getAnnotation(Discriminator.class)))) { beanProperties.add(f.getName()); }/* ww w.j a va 2s. c om*/ ; }, f -> { return f.isAnnotationPresent(Discriminator.class); }); ReflectionUtils.doWithFields(aObject.getClass(), f -> { if (aName.equals(getName(f.getAnnotation(Property.class)))) { beanProperties.add(f.getName()); } ; }, f -> { return f.isAnnotationPresent(Property.class); }); return beanProperties; }
From source file:spring.osgi.utils.OsgiBundleUtils.java
/** * Returns the underlying BundleContext for the given Bundle. This uses * reflection and highly dependent of the OSGi implementation. Should not be * used if OSGi 4.1 is being used.//from w w w .j a v a 2 s . c om * * @param bundle OSGi bundle * @return the bundle context for this bundle */ public static BundleContext getBundleContext(final Bundle bundle) { if (bundle == null) return null; // try Equinox getContext Method meth = ReflectionUtils.findMethod(bundle.getClass(), "getContext", new Class[0]); // fallback to getBundleContext (OSGi 4.1) if (meth == null) meth = ReflectionUtils.findMethod(bundle.getClass(), "getBundleContext", new Class[0]); final Method m = meth; if (meth != null) { ReflectionUtils.makeAccessible(meth); return (BundleContext) ReflectionUtils.invokeMethod(m, bundle); } // fallback to field inspection (KF and Prosyst) final BundleContext[] ctx = new BundleContext[1]; ReflectionUtils.doWithFields(bundle.getClass(), new FieldCallback() { public void doWith(final Field field) throws IllegalArgumentException, IllegalAccessException { ReflectionUtils.makeAccessible(field); ctx[0] = (BundleContext) field.get(bundle); } }, new FieldFilter() { public boolean matches(Field field) { return BundleContext.class.isAssignableFrom(field.getType()); } }); return ctx[0]; }
From source file:org.web4thejob.module.CalendarModule.java
@Override public Collection<L10nString> getLocalizableStrings(final Set<Class> classes) { final Set<Class> localizableModuleClasses = new HashSet<Class>(); final List<L10nString> strings = new ArrayList<L10nString>(); //add here all module classes that need to display localizable resources on external panels localizableModuleClasses.add(CalendarSettingEnum.class); for (Class<?> clazz : localizableModuleClasses) { ReflectionUtils.doWithFields(clazz, new ReflectionUtils.FieldCallback() { @Override//w ww. j a v a 2s . c o m 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()) && classes.contains( ((L10nString) ReflectionUtils.getField(field, null)).getDeclaringClass()); } }); } return strings; }
From source file:com.google.code.simplestuff.bean.BusinessObjectAnnotationParser.java
static Collection<Field> collectAnnotatedFields(Class<? extends Object> clazz) { final List<Field> businessFields = new ArrayList<Field>(); ReflectionUtils.doWithFields(clazz, new FieldCallback() { // simply add each found field to the list public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException { businessFields.add(field);//from ww w. j ava 2s . c om } }, new FieldFilter() { // match fields with the "@BusinessField" annotation public boolean matches(Field field) { return (field.getAnnotation(BusinessField.class) != null); } }); return businessFields; }
From source file:com.ryantenney.metrics.spring.GaugeAnnotationBeanPostProcessor.java
@Override public Object postProcessAfterInitialization(final Object bean, String beanName) { final Class<?> targetClass = AopUtils.getTargetClass(bean); ReflectionUtils.doWithFields(targetClass, new FieldCallback() { @Override/*from ww w .jav a2 s . co m*/ public void doWith(final Field field) throws IllegalAccessException { ReflectionUtils.makeAccessible(field); final Gauge annotation = field.getAnnotation(Gauge.class); final String metricName = Util.forGauge(targetClass, field, annotation); metrics.register(metricName, new com.codahale.metrics.Gauge<Object>() { @Override public Object getValue() { Object value = ReflectionUtils.getField(field, bean); if (value instanceof com.codahale.metrics.Gauge) { value = ((com.codahale.metrics.Gauge<?>) value).getValue(); } return value; } }); LOG.debug("Created gauge {} for field {}.{}", metricName, targetClass.getCanonicalName(), field.getName()); } }, FILTER); ReflectionUtils.doWithMethods(targetClass, new MethodCallback() { @Override public void doWith(final Method method) throws IllegalAccessException { if (method.getParameterTypes().length > 0) { throw new IllegalStateException( "Method " + method.getName() + " is annotated with @Gauge but requires parameters."); } final Gauge annotation = method.getAnnotation(Gauge.class); final String metricName = Util.forGauge(targetClass, method, annotation); metrics.register(metricName, new com.codahale.metrics.Gauge<Object>() { @Override public Object getValue() { return ReflectionUtils.invokeMethod(method, bean); } }); LOG.debug("Created gauge {} for method {}.{}", metricName, targetClass.getCanonicalName(), method.getName()); } }, FILTER); return bean; }
From source file:com.ace.erp.common.inject.support.InjectBaseDependencyHelper.java
/** * ??/*from w w w. ja v a2 s . c om*/ * * @param target * @param annotation */ private static Set<Object> findDependencies(final Object target, final Class<? extends Annotation> annotation) { final Set<Object> candidates = Sets.newHashSet(); ReflectionUtils.doWithFields(target.getClass(), new ReflectionUtils.FieldCallback() { @Override public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException { ReflectionUtils.makeAccessible(field); Object obj = ReflectionUtils.getField(field, target); candidates.add(obj); } }, new ReflectionUtils.FieldFilter() { @Override public boolean matches(Field field) { return field.isAnnotationPresent(annotation); } }); ReflectionUtils.doWithMethods(target.getClass(), new ReflectionUtils.MethodCallback() { @Override public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException { ReflectionUtils.makeAccessible(method); PropertyDescriptor descriptor = BeanUtils.findPropertyForMethod(method); candidates.add(ReflectionUtils.invokeMethod(descriptor.getReadMethod(), target)); } }, new ReflectionUtils.MethodFilter() { @Override public boolean matches(Method method) { boolean hasAnnotation = false; hasAnnotation = method.isAnnotationPresent(annotation); if (!hasAnnotation) { return false; } boolean hasReadMethod = false; PropertyDescriptor descriptor = BeanUtils.findPropertyForMethod(method); hasReadMethod = descriptor != null && descriptor.getReadMethod() != null; if (!hasReadMethod) { return false; } return true; } }); return candidates; }
From source file:com.ryantenney.metrics.spring.InjectMetricAnnotationBeanPostProcessor.java
@Override public Object postProcessAfterInitialization(final Object bean, String beanName) { final Class<?> targetClass = AopUtils.getTargetClass(bean); ReflectionUtils.doWithFields(targetClass, new FieldCallback() { @Override/*w w w. ja v a 2 s . c om*/ public void doWith(Field field) throws IllegalAccessException { final InjectMetric annotation = field.getAnnotation(InjectMetric.class); final String metricName = Util.forInjectMetricField(targetClass, field, annotation); final Class<?> type = field.getType(); Metric metric = null; if (Meter.class == type) { metric = metrics.meter(metricName); } else if (Timer.class == type) { metric = metrics.timer(metricName); } else if (Counter.class == type) { metric = metrics.counter(metricName); } else if (Histogram.class == type) { metric = metrics.histogram(metricName); } else { throw new IllegalStateException("Cannot inject a metric of type " + type.getCanonicalName()); } ReflectionUtils.makeAccessible(field); ReflectionUtils.setField(field, bean, metric); LOG.debug("Injected metric {} for field {}.{}", metricName, targetClass.getCanonicalName(), field.getName()); } }, FILTER); return bean; }
From source file:tv.arte.resteventapi.core.presentation.decoration.RestEventApiDecorationProvider.java
/** * Retrieve a decoration context related to a given bean * /*from ww w . ja v a 2 s.com*/ * @param bean A given bean * @return A map with field names as keys and appropriate objects as values */ public static Map<String, ?> getBeanDecorationContext(final Object bean) { Map<String, Object> decorationContext = new LinkedHashMap<String, Object>(); //Construct Hateoas self referencing link if (hrefedBeansControllerMethodMapping.containsKey(bean.getClass())) { Method method = hrefedBeansControllerMethodMapping.get(bean.getClass()); final Map<String, Object> paramValue = new LinkedHashMap<String, Object>(); ReflectionUtils.doWithFields(bean.getClass(), new FieldCallback() { public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException { String hrefedValue = field.getAnnotation(HrefedParamField.class).value(); if (StringUtils.isBlank(hrefedValue)) { hrefedValue = field.getName(); } Object fieldValue = null; try { fieldValue = PropertyUtils.getProperty(bean, field.getName()); } catch (Exception e) { throw new RestEventApiRuntimeException("Unable to access the bean property value."); } if (fieldValue != null) { paramValue.put(hrefedValue, fieldValue); } } }, new FieldFilter() { public boolean matches(Field field) { return field.isAnnotationPresent(HrefedParamField.class); } }); decorationContext.put(HATEOAS_HREF_KEY, RestEventApiControllerLinkBuilder .linkTo(method.getDeclaringClass(), method, paramValue, conversionService)); } return decorationContext; }
From source file:py.una.pol.karaku.test.test.ValidationMessagesTest.java
@Test public void testConstants() { ReflectionUtils.doWithFields(ValidationMessages.class, new FieldCallback() { @Override//w w w . j a v a2s . c o m public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException { String value = (String) field.get(null); assertNotNull(value); assertTrue("Key: " + value + " not found", keys.contains(value)); } }, new FieldFilter() { @Override public boolean matches(Field field) { int modifiers = field.getModifiers(); return Modifier.isStatic(modifiers) && !Modifier.isTransient(modifiers) && Modifier.isPublic(modifiers); } }); }