Java Code Examples for org.springframework.util.ReflectionUtils#doWithFields()
The following examples show how to use
org.springframework.util.ReflectionUtils#doWithFields() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: StringEqualsTest.java From spring-boot-cookbook with Apache License 2.0 | 7 votes |
@Test public void springReflectionUtilsTest1() { final List<String> list = new ArrayList<String>(); TwoLevelChildClass twoLevelChildClass = new TwoLevelChildClass(); twoLevelChildClass.setTwoLevelChildName("TwoLevelChildName"); twoLevelChildClass.setOneLevelChildName("OneLevelChildName"); twoLevelChildClass.setName("Name"); ReflectionUtils.doWithFields(TwoLevelChildClass.class, new ReflectionUtils.FieldCallback() { public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException { list.add(field.getName()); field.setAccessible(true);//Class org.springframework.util.ReflectionUtils can not access a member of class com.tangcheng.learning.reflect.StringEqualsTest$TwoLevelChildClass with modifiers "private" Object o = ReflectionUtils.getField(field, twoLevelChildClass); System.out.println(o); // TwoLevelChildName \n OneLevelChildName \n Name } }); System.out.println(list); //[twoLevelChildName, oneLevelChildName, name] }
Example 2
Source File: DefaultDictApply.java From hsweb-framework with Apache License 2.0 | 6 votes |
protected DictWrapper createCache(Class bean) { StringBuilder method = new StringBuilder() .append("public void wrap(Object bean, org.hswebframework.web.dict.DictDefineRepository repository)") .append("{\n") .append(bean.getName()).append(" target=(").append(bean.getName()).append(")bean;\n"); ReflectionUtils.doWithFields(bean, field -> { Class type = field.getType(); if (type.isArray()) { type = type.getComponentType(); } //枚举字典并且枚举数量大于64 if (type.isEnum() && EnumDict.class.isAssignableFrom(type) && type.getEnumConstants().length >= 64) { } }); method.append("\n}"); return DictWrapper.empty; }
Example 3
Source File: Response.java From SeimiCrawler with Apache License 2.0 | 6 votes |
private <T> T parse(Class<T> target, String text) throws Exception { T bean = target.newInstance(); final List<Field> props = new LinkedList<>(); ReflectionUtils.doWithFields(target, props::add); JXDocument jxDocument = JXDocument.create(text); for (Field f:props){ Xpath xpathInfo = f.getAnnotation(Xpath.class); if (xpathInfo!=null){ String xpath = xpathInfo.value(); List<Object> res = jxDocument.sel(xpath); synchronized (f){ boolean accessFlag = f.isAccessible(); f.setAccessible(true); f.set(bean,defaultCastToTargetValue(target, f, res)); f.setAccessible(accessFlag); } } } return bean; }
Example 4
Source File: RaftAnnotationBeanPostProcessor.java From sofa-registry with Apache License 2.0 | 6 votes |
private void processRaftReference(Object bean) { final Class<?> beanClass = bean.getClass(); ReflectionUtils.doWithFields(beanClass, field -> { RaftReference referenceAnnotation = field.getAnnotation(RaftReference.class); if (referenceAnnotation == null) { return; } Class<?> interfaceType = referenceAnnotation.interfaceType(); if (interfaceType.equals(void.class)) { interfaceType = field.getType(); } String serviceId = getServiceId(interfaceType, referenceAnnotation.uniqueId()); Object proxy = getProxy(interfaceType, serviceId); ReflectionUtils.makeAccessible(field); ReflectionUtils.setField(field, bean, proxy); }, field -> !Modifier.isStatic(field.getModifiers()) && field.isAnnotationPresent(RaftReference.class)); }
Example 5
Source File: CascadeCallback.java From tutorials with MIT License | 6 votes |
@Override public void doWith(final Field field) throws IllegalArgumentException, IllegalAccessException { ReflectionUtils.makeAccessible(field); if (field.isAnnotationPresent(DBRef.class) && field.isAnnotationPresent(CascadeSave.class)) { final Object fieldValue = field.get(getSource()); if (fieldValue != null) { final FieldCallback callback = new FieldCallback(); ReflectionUtils.doWithFields(fieldValue.getClass(), callback); getMongoOperations().save(fieldValue); } } }
Example 6
Source File: PropertyMatches.java From spring-analysis-note with MIT License | 5 votes |
private static String[] calculateMatches(final String name, Class<?> clazz, final int maxDistance) { final List<String> candidates = new ArrayList<>(); ReflectionUtils.doWithFields(clazz, field -> { String possibleAlternative = field.getName(); if (calculateStringDistance(name, possibleAlternative) <= maxDistance) { candidates.add(possibleAlternative); } }); Collections.sort(candidates); return StringUtils.toStringArray(candidates); }
Example 7
Source File: DynamoDBHashAndRangeKeyExtractingEntityMetadataImpl.java From spring-data-dynamodb with Apache License 2.0 | 5 votes |
@Override public Set<String> getIndexRangeKeyPropertyNames() { final Set<String> propertyNames = new HashSet<String>(); ReflectionUtils.doWithMethods(getJavaType(), new MethodCallback() { public void doWith(Method method) { if (method.getAnnotation(DynamoDBIndexRangeKey.class) != null) { if ((method.getAnnotation(DynamoDBIndexRangeKey.class).localSecondaryIndexName() != null && method .getAnnotation(DynamoDBIndexRangeKey.class).localSecondaryIndexName().trim().length() > 0) || (method.getAnnotation(DynamoDBIndexRangeKey.class).localSecondaryIndexNames() != null && method .getAnnotation(DynamoDBIndexRangeKey.class).localSecondaryIndexNames().length > 0)) { propertyNames.add(getPropertyNameForAccessorMethod(method)); } } } }); ReflectionUtils.doWithFields(getJavaType(), new FieldCallback() { public void doWith(Field field) { if (field.getAnnotation(DynamoDBIndexRangeKey.class) != null) { if ((field.getAnnotation(DynamoDBIndexRangeKey.class).localSecondaryIndexName() != null && field .getAnnotation(DynamoDBIndexRangeKey.class).localSecondaryIndexName().trim().length() > 0) || (field.getAnnotation(DynamoDBIndexRangeKey.class).localSecondaryIndexNames() != null && field .getAnnotation(DynamoDBIndexRangeKey.class).localSecondaryIndexNames().length > 0)) { propertyNames.add(getPropertyNameForField(field)); } } } }); return propertyNames; }
Example 8
Source File: InjectAnnotationBeanPostProcessor.java From spring-boot-starter-dubbo with Apache License 2.0 | 5 votes |
private List<InjectionMetadata.InjectedElement> findFieldReferenceMetadata(final Class<?> beanClass) { final List<InjectionMetadata.InjectedElement> elements = new LinkedList<InjectionMetadata.InjectedElement>(); ReflectionUtils.doWithFields(beanClass, new ReflectionUtils.FieldCallback() { @Override public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException { Inject inject = findReferenceAnnotation(field); if (inject == null) { return; } if (Modifier.isStatic(field.getModifiers())) { logger.warn("@Reference 静态方法不支持注释: {}" , field); return; } Class<?> requiredType = field.getDeclaringClass(); Object bean= getBean(inject, requiredType); if(bean!=null){ elements.add(injectBeanPostProcessor.createAutowiredFieldElement(field, true)); return; } elements.add(new ReferenceFieldElement(field, inject.value())); } }); return elements; }
Example 9
Source File: PropertyMatches.java From lams with GNU General Public License v2.0 | 5 votes |
private static String[] calculateMatches(final String propertyName, Class<?> beanClass, final int maxDistance) { final List<String> candidates = new ArrayList<String>(); ReflectionUtils.doWithFields(beanClass, new ReflectionUtils.FieldCallback() { @Override public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException { String possibleAlternative = field.getName(); if (calculateStringDistance(propertyName, possibleAlternative) <= maxDistance) { candidates.add(possibleAlternative); } } }); Collections.sort(candidates); return StringUtils.toStringArray(candidates); }
Example 10
Source File: PropertyMatches.java From spring4-understanding with Apache License 2.0 | 5 votes |
private static String[] calculateMatches(final String propertyName, Class<?> beanClass, final int maxDistance) { final List<String> candidates = new ArrayList<String>(); ReflectionUtils.doWithFields(beanClass, new ReflectionUtils.FieldCallback() { @Override public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException { String possibleAlternative = field.getName(); if (calculateStringDistance(propertyName, possibleAlternative) <= maxDistance) { candidates.add(possibleAlternative); } } }); Collections.sort(candidates); return StringUtils.toStringArray(candidates); }
Example 11
Source File: AbstractAnnotationBeanPostProcessor.java From spring-context-support with Apache License 2.0 | 5 votes |
/** * Finds {@link InjectionMetadata.InjectedElement} Metadata from annotated fields * * @param beanClass The {@link Class} of Bean * @return non-null {@link List} */ private List<AbstractAnnotationBeanPostProcessor.AnnotatedFieldElement> findFieldAnnotationMetadata(final Class<?> beanClass) { final List<AbstractAnnotationBeanPostProcessor.AnnotatedFieldElement> elements = new LinkedList<AbstractAnnotationBeanPostProcessor.AnnotatedFieldElement>(); ReflectionUtils.doWithFields(beanClass, new ReflectionUtils.FieldCallback() { @Override public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException { for (Class<? extends Annotation> annotationType : getAnnotationTypes()) { AnnotationAttributes attributes = getAnnotationAttributes(field, annotationType, getEnvironment(), true, true); if (attributes != null) { if (Modifier.isStatic(field.getModifiers())) { if (logger.isWarnEnabled()) { logger.warn("@" + annotationType.getName() + " is not supported on static fields: " + field); } return; } elements.add(new AnnotatedFieldElement(field, attributes)); } } } }); return elements; }
Example 12
Source File: AnnotationInjectedBeanPostProcessor.java From spring-context-support with Apache License 2.0 | 5 votes |
/** * Finds {@link InjectionMetadata.InjectedElement} Metadata from annotated {@link A} fields * * @param beanClass The {@link Class} of Bean * @return non-null {@link List} */ private List<AnnotatedFieldElement> findFieldAnnotationMetadata(final Class<?> beanClass) { final List<AnnotatedFieldElement> elements = new LinkedList<AnnotatedFieldElement>(); ReflectionUtils.doWithFields(beanClass, new ReflectionUtils.FieldCallback() { @Override public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException { A annotation = getAnnotation(field, getAnnotationType()); if (annotation != null) { if (Modifier.isStatic(field.getModifiers())) { if (logger.isWarnEnabled()) { logger.warn("@" + getAnnotationType().getName() + " is not supported on static fields: " + field); } return; } elements.add(new AnnotatedFieldElement(field, annotation)); } } }); return elements; }
Example 13
Source File: JsfBeansAnnotationPostProcessor.java From joinfaces with Apache License 2.0 | 5 votes |
@Override public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { ReflectionUtils.doWithFields(bean.getClass(), field -> this.suppliers.forEach((annotation, supplier) -> { if (AnnotatedElementUtils.hasAnnotation(field, annotation)) { ReflectionUtils.makeAccessible(field); ReflectionUtils.setField(field, bean, supplier.get()); } }), this::isAutowiredField); return bean; }
Example 14
Source File: ApimlLogInjector.java From api-layer with Eclipse Public License 2.0 | 5 votes |
@Override public Object postProcessBeforeInitialization(final Object bean, @Nonnull String name) { ReflectionUtils.doWithFields(bean.getClass(), field -> { // make the field accessible if defined private ReflectionUtils.makeAccessible(field); if (field.getAnnotation(InjectApimlLogger.class) != null) { Class clazz = getClass(bean); ApimlLogger log = ApimlLogger.of(clazz, YamlMessageServiceInstance.getInstance()); field.set(bean, log); } }); return bean; }
Example 15
Source File: AbstractTestActionConverter.java From citrus-admin with Apache License 2.0 | 5 votes |
@Override public TestActionModel convert(S model) { TestActionModel actionModel = new TestActionModel(getActionType(), getSourceModelClass()); ReflectionUtils.doWithFields(getSourceModelClass(), field -> { Property property = property(field.getName(), getDisplayName(getFieldName(field.getName())), model, getDefaultValue(field), isRequiredField(field)) .options(getFieldOptions(field)) .optionType(getOptionType(field)); actionModel.add(property); }, field -> include(model, field)); return actionModel; }
Example 16
Source File: PropertyMatches.java From java-technology-stack with MIT License | 5 votes |
private static String[] calculateMatches(final String name, Class<?> clazz, final int maxDistance) { final List<String> candidates = new ArrayList<>(); ReflectionUtils.doWithFields(clazz, field -> { String possibleAlternative = field.getName(); if (calculateStringDistance(name, possibleAlternative) <= maxDistance) { candidates.add(possibleAlternative); } }); Collections.sort(candidates); return StringUtils.toStringArray(candidates); }
Example 17
Source File: XxlConfFactory.java From xxl-conf with GNU General Public License v3.0 | 5 votes |
@Override public boolean postProcessAfterInstantiation(final Object bean, final String beanName) throws BeansException { // 1、Annotation('@XxlConf'):resolves conf + watch if (!beanName.equals(this.beanName)) { ReflectionUtils.doWithFields(bean.getClass(), new ReflectionUtils.FieldCallback() { @Override public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException { if (field.isAnnotationPresent(XxlConf.class)) { String propertyName = field.getName(); XxlConf xxlConf = field.getAnnotation(XxlConf.class); String confKey = xxlConf.value(); String confValue = XxlConfClient.get(confKey, xxlConf.defaultValue()); // resolves placeholders BeanRefreshXxlConfListener.BeanField beanField = new BeanRefreshXxlConfListener.BeanField(beanName, propertyName); refreshBeanField(beanField, confValue, bean); // watch if (xxlConf.callback()) { BeanRefreshXxlConfListener.addBeanField(confKey, beanField); } } } }); } return super.postProcessAfterInstantiation(bean, beanName); }
Example 18
Source File: ReConfigurableBeanAdapter.java From haven-platform with Apache License 2.0 | 4 votes |
private void load() { ReflectionUtils.doWithMethods(this.type, (m) -> { if(!m.isAnnotationPresent(ReConfigObject.class)) { return; } int pc = m.getParameterCount(); final boolean returnVoid = Void.TYPE.equals(m.getReturnType()); // note that in future we may pass ConfigReadContext into this methods, then we must to update below conditions boolean getter = pc == 0 && !returnVoid; boolean setter = pc == 1 && returnVoid; if(!getter && !setter) { return; } if(getter) { Assert.isNull(this.supplier, "Can not override existed getter with: " + m); makeAccessible(m); this.supplier = new GetterSupplier(m); } else { Assert.isNull(this.consumer, "Can not override existed consumer with: " + m); makeAccessible(m); this.consumer = new SetterConsumer(m); } }); if(this.supplier != null && this.consumer != null) { return; } ReflectionUtils.doWithFields(this.type, (f) -> { if(!f.isAnnotationPresent(ReConfigObject.class)) { return; } if(Modifier.isStatic(f.getModifiers())) { throw new IllegalStateException("Static field '" + f + "' must not be annotated with " + ReConfigObject.class ); } if(this.supplier == null) { makeAccessible(f); this.supplier = new FieldSupplier(f); } if(this.consumer == null && !Modifier.isFinal(f.getModifiers())) { makeAccessible(f); this.consumer = new FieldConsumer(f); } }); if(this.supplier == null || this.consumer == null) { throw new RuntimeException("Can not extract setter (" + this.consumer + ") and/or getter (" + this.supplier + ") from annotated bean: " + name); } }
Example 19
Source File: StubRunnerPortBeanPostProcessor.java From spring-cloud-contract with Apache License 2.0 | 4 votes |
private void injectStubRunnerPort(Object bean) { Class<?> clazz = bean.getClass(); ReflectionUtils.FieldCallback fieldCallback = new StubRunnerPortFieldCallback( this.environment, bean); ReflectionUtils.doWithFields(clazz, fieldCallback); }
Example 20
Source File: CompensableAnnotationProcessor.java From servicecomb-pack with Apache License 2.0 | 4 votes |
private void checkFields(Object bean) { ReflectionUtils.doWithFields(bean.getClass(), new ExecutorFieldCallback(bean, omegaContext)); }