/** * Attempt to find a {@link Field field} on the supplied {@link Class} with the * supplied {@code name}. Searches all superclasses up to {@link Object}. * @param clazz the class to introspect * @param name the name of the field * @return the corresponding Field object, or {@code null} if not found */ @Nullable public static Field findField(Class<?> clazz, String name) { return findField(clazz, name, null); }
public String getUserField(Class type) { if (ReflectionUtils.findField(type, "userId") != null) { return "userId"; } return "creatorId"; }
/** * Attempt to find a {@link Field field} on the supplied {@link Class} with the * supplied {@code name}. Searches all superclasses up to {@link Object}. * @param clazz the class to introspect * @param name the name of the field * @return the corresponding Field object, or {@code null} if not found */ @Nullable public static Field findField(Class<?> clazz, String name) { return findField(clazz, name, null); }
private ConfigurableBeanFactory getBeanFactory(Object enhancedConfigInstance) { Field field = ReflectionUtils.findField(enhancedConfigInstance.getClass(), BEAN_FACTORY_FIELD); Assert.state(field != null, "Unable to find generated bean factory field"); Object beanFactory = ReflectionUtils.getField(field, enhancedConfigInstance); Assert.state(beanFactory != null, "BeanFactory has not been injected into @Configuration class"); Assert.state(beanFactory instanceof ConfigurableBeanFactory, "Injected BeanFactory is not a ConfigurableBeanFactory"); return (ConfigurableBeanFactory) beanFactory; }
private <T> T getFieldValue(Object object, String fieldName, Class<T> fieldType) { Field field = ReflectionUtils.findField(object.getClass(), fieldName, fieldType); ReflectionUtils.makeAccessible(field); return (T) ReflectionUtils.getField(field, object); }
private <T> T getFieldValue(Object object, String fieldName, Class<T> fieldType) { Field field = ReflectionUtils.findField(object.getClass(), fieldName, fieldType); ReflectionUtils.makeAccessible(field); return (T) ReflectionUtils.getField(field, object); }
@Override @Nullable public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable { Field field = ReflectionUtils.findField(obj.getClass(), BEAN_FACTORY_FIELD); Assert.state(field != null, "Unable to find generated BeanFactory field"); field.set(obj, args[0]); // Does the actual (non-CGLIB) superclass implement BeanFactoryAware? // If so, call its setBeanFactory() method. If not, just exit. if (BeanFactoryAware.class.isAssignableFrom(ClassUtils.getUserClass(obj.getClass().getSuperclass()))) { return proxy.invokeSuper(obj, args); } return null; }
private Object getFieldValue(Object instance, String fieldName) { Field field = ReflectionUtils.findField(instance.getClass(), fieldName); field.setAccessible(true); try { return field.get(instance); } catch (IllegalAccessException e) { // ignore } return null; }
@Override @Nullable protected FieldPropertyHandler getLocalPropertyHandler(String propertyName) { FieldPropertyHandler propertyHandler = this.fieldMap.get(propertyName); if (propertyHandler == null) { Field field = ReflectionUtils.findField(getWrappedClass(), propertyName); if (field != null) { propertyHandler = new FieldPropertyHandler(field); this.fieldMap.put(propertyName, propertyHandler); } } return propertyHandler; }
private ConfigurableBeanFactory getBeanFactory(Object enhancedConfigInstance) { Field field = ReflectionUtils.findField(enhancedConfigInstance.getClass(), BEAN_FACTORY_FIELD); Assert.state(field != null, "Unable to find generated bean factory field"); Object beanFactory = ReflectionUtils.getField(field, enhancedConfigInstance); Assert.state(beanFactory != null, "BeanFactory has not been injected into @Configuration class"); Assert.state(beanFactory instanceof ConfigurableBeanFactory, "Injected BeanFactory is not a ConfigurableBeanFactory"); return (ConfigurableBeanFactory) beanFactory; }
protected Object getEnumValue(String asmTypeDescriptor, String attributeValue) { Object valueToUse = attributeValue; try { Class<?> enumType = ClassUtils.forName(Type.getType(asmTypeDescriptor).getClassName(), this.classLoader); Field enumConstant = ReflectionUtils.findField(enumType, attributeValue); if (enumConstant != null) { ReflectionUtils.makeAccessible(enumConstant); valueToUse = enumConstant.get(null); } } catch (ClassNotFoundException | NoClassDefFoundError ex) { logger.debug("Failed to classload enum type while reading annotation metadata", ex); } catch (IllegalAccessException | AccessControlException ex) { logger.debug("Could not access enum value while reading annotation metadata", ex); } return valueToUse; }
@Nullable private Field getField() { String name = getName(); if (!StringUtils.hasLength(name)) { return null; } Field field = null; Class<?> declaringClass = declaringClass(); if (declaringClass != null) { field = ReflectionUtils.findField(declaringClass, name); if (field == null) { // Same lenient fallback checking as in CachedIntrospectionResults... field = ReflectionUtils.findField(declaringClass, StringUtils.uncapitalize(name)); if (field == null) { field = ReflectionUtils.findField(declaringClass, StringUtils.capitalize(name)); } } } return field; }
Field transformer = ReflectionUtils.findField(classLoader.getClass(), "transformer"); if (transformer == null) { throw new IllegalArgumentException("Could not find 'transformer' field on JBoss ClassLoader: " +
@Override @Nullable public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable { Field field = ReflectionUtils.findField(obj.getClass(), BEAN_FACTORY_FIELD); Assert.state(field != null, "Unable to find generated BeanFactory field"); field.set(obj, args[0]); // Does the actual (non-CGLIB) superclass implement BeanFactoryAware? // If so, call its setBeanFactory() method. If not, just exit. if (BeanFactoryAware.class.isAssignableFrom(ClassUtils.getUserClass(obj.getClass().getSuperclass()))) { return proxy.invokeSuper(obj, args); } return null; }
private void clear(Service service, String fieldName, Class<?> fieldType) { Field field = ReflectionUtils.findField(Service.class, fieldName); field.setAccessible(true); Object routes = ReflectionUtils.getField(field, service); ReflectionUtils.invokeMethod(ReflectionUtils.findMethod(fieldType, "clear"), routes); } }
@Test public void findField() { Field field = ReflectionUtils.findField(TestObjectSubclassWithPublicField.class, "publicField", String.class); assertNotNull(field); assertEquals("publicField", field.getName()); assertEquals(String.class, field.getType()); assertTrue("Field should be public.", Modifier.isPublic(field.getModifiers())); field = ReflectionUtils.findField(TestObjectSubclassWithNewField.class, "prot", String.class); assertNotNull(field); assertEquals("prot", field.getName()); assertEquals(String.class, field.getType()); assertTrue("Field should be protected.", Modifier.isProtected(field.getModifiers())); field = ReflectionUtils.findField(TestObjectSubclassWithNewField.class, "name", String.class); assertNotNull(field); assertEquals("name", field.getName()); assertEquals(String.class, field.getType()); assertTrue("Field should be private.", Modifier.isPrivate(field.getModifiers())); }
@Test public void customPathMatchConfig() { ApplicationContext context = loadConfig(CustomPatchMatchConfig.class); final Field field = ReflectionUtils.findField(PathPatternParser.class, "matchOptionalTrailingSeparator"); ReflectionUtils.makeAccessible(field); String name = "requestMappingHandlerMapping"; RequestMappingHandlerMapping mapping = context.getBean(name, RequestMappingHandlerMapping.class); assertNotNull(mapping); PathPatternParser patternParser = mapping.getPathPatternParser(); assertNotNull(patternParser); boolean matchOptionalTrailingSlash = (boolean) ReflectionUtils.getField(field, patternParser); assertFalse(matchOptionalTrailingSlash); Map<RequestMappingInfo, HandlerMethod> map = mapping.getHandlerMethods(); assertEquals(1, map.size()); assertEquals(Collections.singleton(new PathPatternParser().parse("/api/user/{id}")), map.keySet().iterator().next().getPatternsCondition().getPatterns()); }
@Test public void setField() { TestObjectSubclassWithNewField testBean = new TestObjectSubclassWithNewField(); Field field = ReflectionUtils.findField(TestObjectSubclassWithNewField.class, "name", String.class); ReflectionUtils.makeAccessible(field); ReflectionUtils.setField(field, testBean, "FooBar"); assertNotNull(testBean.getName()); assertEquals("FooBar", testBean.getName()); ReflectionUtils.setField(field, testBean, null); assertNull(testBean.getName()); }
@Test public void requestMappingHandlerMapping() throws Exception { ApplicationContext context = loadConfig(WebFluxConfig.class); final Field field = ReflectionUtils.findField(PathPatternParser.class, "matchOptionalTrailingSeparator"); ReflectionUtils.makeAccessible(field); String name = "requestMappingHandlerMapping"; RequestMappingHandlerMapping mapping = context.getBean(name, RequestMappingHandlerMapping.class); assertNotNull(mapping); assertEquals(0, mapping.getOrder()); PathPatternParser patternParser = mapping.getPathPatternParser(); assertNotNull(patternParser); boolean matchOptionalTrailingSlash = (boolean) ReflectionUtils.getField(field, patternParser); assertTrue(matchOptionalTrailingSlash); name = "webFluxContentTypeResolver"; RequestedContentTypeResolver resolver = context.getBean(name, RequestedContentTypeResolver.class); assertSame(resolver, mapping.getContentTypeResolver()); ServerWebExchange exchange = MockServerWebExchange.from(get("/path").accept(MediaType.APPLICATION_JSON)); assertEquals(Collections.singletonList(MediaType.APPLICATION_JSON), resolver.resolveMediaTypes(exchange)); }
rbd.setFactoryMethodName("createMock"); rbd.getConstructorArgumentValues().addGenericArgumentValue(Repository.class); rbd.setQualifiedElement(ReflectionUtils.findField(getClass(), "integerRepositoryQualifierProvider")); bf.registerBeanDefinition("integerRepository", rbd); // Bean name not matching qualifier