Example usage for org.springframework.util ReflectionUtils doWithFields

List of usage examples for org.springframework.util ReflectionUtils doWithFields

Introduction

In this page you can find the example usage for org.springframework.util ReflectionUtils doWithFields.

Prototype

public static void doWithFields(Class<?> clazz, FieldCallback fc) 

Source Link

Document

Invoke the given callback on all fields in the target class, going up the class hierarchy to get all declared fields.

Usage

From source file:cn.wanghaomiao.seimi.core.SeimiBeanResolver.java

public static <T> T parse(Class<T> target, String text) throws Exception {
    T bean = target.newInstance();// ww  w.  j av  a  2  s. c  o  m
    final List<Field> props = new LinkedList<>();
    ReflectionUtils.doWithFields(target, new ReflectionUtils.FieldCallback() {
        @Override
        public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException {
            props.add(field);
        }
    });
    JXDocument jxDocument = new JXDocument(text);
    for (Field f : props) {
        Xpath xpathInfo = f.getAnnotation(Xpath.class);
        if (xpathInfo != null) {
            String xpath = xpathInfo.value();
            List<Object> res = jxDocument.sel(xpath);
            boolean accessFlag = f.isAccessible();
            f.setAccessible(true);
            f.set(bean, defaultCastToTargetValue(target, f, res));
            f.setAccessible(accessFlag);
        }
    }
    return bean;
}

From source file:com.aestheticsw.jobkeywords.shared.config.LogInjector.java

@Override
public Object postProcessBeforeInitialization(final Object bean, String name) throws BeansException {
    ReflectionUtils.doWithFields(bean.getClass(), new ReflectionUtils.FieldCallback() {
        public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException {
            // make the field accessible if defined private
            ReflectionUtils.makeAccessible(field);
            if (field.getAnnotation(Log.class) != null) {
                Logger log = LoggerFactory.getLogger(bean.getClass());
                field.set(bean, log);/*from w w  w.  ja  v a 2 s  .  c  o m*/
            }
        }
    });
    return bean;
}

From source file:org.jdal.annotation.AnnotatedElementAccessor.java

/**
 * Find annotated elements on types/*from   www  . j  a v  a  2  s.  co  m*/
 * @param ann annotation to search
 * @param clazz class to search on.
 * @return List with annotated elements
 */
public static List<AnnotatedElement> findAnnotatedElements(final Class<? extends Annotation> annotationType,
        Class<?> clazz) {
    final ArrayList<AnnotatedElement> elements = new ArrayList<AnnotatedElement>();
    // Lookup fields
    ReflectionUtils.doWithFields(clazz, new FieldCallback() {

        @Override
        public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException {
            if (field.getAnnotation(annotationType) != null) {
                elements.add(field);
            }

        }
    });
    // Lookup methods
    ReflectionUtils.doWithMethods(clazz, new MethodCallback() {

        @Override
        public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException {

            if (org.springframework.core.annotation.AnnotationUtils.getAnnotation(method,
                    annotationType) != null)
                elements.add(method);
        }
    });

    return elements;
}

From source file:eu.artofcoding.beetlejuice.spring.Slf4jPostProcessor.java

public Object postProcessBeforeInitialization(final Object bean, final String beanName) throws BeansException {
    ReflectionUtils.doWithFields(bean.getClass(), new ReflectionUtils.FieldCallback() {
        @SuppressWarnings("unchecked")
        public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException {
            ReflectionUtils.makeAccessible(field);
            // Check if the field is annoted with @Slf4j
            if (field.getAnnotation(Slf4j.class) != null) {
                logger.debug("Injecting Logger into " + beanName + "/" + bean.getClass());
                //Slf4j slf4jAnnotation = field.getAnnotation(Slf4j.class);
                Logger logger = LoggerFactory.getLogger(bean.getClass());
                field.set(bean, logger);
            }/* w ww . j  av a 2 s .c o m*/
        }
    });
    return bean;
}

From source file:com.wiiyaya.framework.provider.repository.revision.entity.ReflectionRevisionEntityInformation.java

public ReflectionRevisionEntityInformation(Class<?> revisionEntityClass) {

    Assert.notNull(revisionEntityClass);

    AnnotationDetectionFieldCallback fieldCallback = new AnnotationDetectionFieldCallback(RevisionNumber.class);
    ReflectionUtils.doWithFields(revisionEntityClass, fieldCallback);

    this.revisionNumberType = fieldCallback.getType();
    this.revisionEntityClass = revisionEntityClass;

}

From source file:almira.sample.util.LogPostProcessor.java

@Override
public Object postProcessBeforeInitialization(final Object bean, String beanName) {
    ReflectionUtils.doWithFields(bean.getClass(), new FieldCallback() {
        @Override/*w w  w. j a va2 s .c  om*/
        public void doWith(Field field) throws IllegalAccessException {
            ReflectionUtils.makeAccessible(field);
            if (field.getAnnotation(Log.class) != null) {
                Logger logger = LoggerFactory.getLogger(bean.getClass().getName());
                field.set(bean, logger);
            }
        }
    });
    return bean;
}

From source file:com.greenline.hrs.admin.web.war.conf.InjectBeanPostProcessor.java

private void injectPropertyToBean(final Object bean) {
    ReflectionUtils.doWithFields(bean.getClass(), new ReflectionUtils.FieldCallback() {

        @Override/*from   ww  w. j a  va  2s.c  om*/
        public void doWith(Field field) throws IllegalAccessException {
            InjectingProperty annotation = field.getAnnotation(InjectingProperty.class);
            if (annotation != null) {
                Object strValue = propertyConfigurer.getProperty(annotation.value());
                if (null != strValue) {
                    Object value = typeConverter.convertIfNecessary(strValue, field.getType());
                    ReflectionUtils.makeAccessible(field);
                    if (Modifier.isStatic(field.getModifiers())) {
                        field.set(null, value);
                    } else {
                        field.set(bean, value);
                    }
                }
            }
        }
    });
}

From source file:org.shept.persistence.provider.hibernate.HibernateUtils_old.java

/**
 * Checking if it is a new model// ww w .j  av a 2s.c om
 * If the index is a compound index we must check all components if they are all non null
 * @param index
 * @return
 */
public static boolean isNewModel(HibernateDaoSupport dao, Object model) {
    final Object index = getIdValue(dao, model);
    final List<Field> nulls = new ArrayList<Field>();
    if (index == null)
        return true;

    ReflectionUtils.doWithFields(index.getClass(), new ReflectionUtils.FieldCallback() {
        public void doWith(Field field) {
            try {
                Method idMth = ReflectionUtils.findMethod(index.getClass(),
                        "get" + StringUtils.capitalize(field.getName()));
                Object value = ReflectionUtils.invokeMethod(idMth, index);
                if (value == null) {
                    nulls.add(field);
                }
            } catch (Exception ex) {
                // ignore all Exception here as they are quit frequent
                // e.g. serialVersionUid e.t.c. or do better filtering
                // TODO better eliminate error cases
            }
        }
    });
    return nulls.size() > 0;
}

From source file:com.blstream.hooks.springframework.mongodb.event.CollectionCascadingMongoEventListener.java

public void onBeforeConvert(final Object source) {
    ReflectionUtils.doWithFields(source.getClass(), new ReflectionUtils.FieldCallback() {

        @Override/*from   w  w  w  . j  ava 2s  . co m*/
        public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException {
            ReflectionUtils.makeAccessible(field);

            if (field.isAnnotationPresent(DBRef.class)
                    && field.isAnnotationPresent(DBRefCollectionCascade.class)) {
                final Object fieldValue = field.get(source);

                if (fieldValue instanceof Collection<?>) {
                    Collection<?> collection = (Collection<?>) fieldValue;

                    for (Object collectionElement : collection) {
                        DbRefFieldCallback callback = new DbRefFieldCallback();

                        ReflectionUtils.doWithFields(collectionElement.getClass(), callback);

                        if (!callback.isIdFound()) {
                            throw new MappingException(
                                    "Cannot perform cascade save on child object without id set");
                        }

                        mongoOperations.save(collectionElement);
                    }
                }
            }
        }
    });
}

From source file:com.blstream.hooks.springframework.mongodb.event.CascadingMongoEventListener.java

public void onBeforeConvert(final Object source) {
    ReflectionUtils.doWithFields(source.getClass(), new ReflectionUtils.FieldCallback() {

        @Override//from  w w  w  .j  a v  a  2 s  . c  om
        public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException {
            ReflectionUtils.makeAccessible(field);

            if (field.isAnnotationPresent(DBRef.class) && field.isAnnotationPresent(DBRefCascade.class)) {
                final Object fieldValue = field.get(source);

                DbRefFieldCallback callback = new DbRefFieldCallback();

                ReflectionUtils.doWithFields(fieldValue.getClass(), callback);

                if (!callback.isIdFound()) {
                    throw new MappingException("Cannot perform cascade save on child object without id set");
                }

                mongoOperations.save(fieldValue);
            }
        }
    });
}