Example usage for java.lang.reflect Field getModifiers

List of usage examples for java.lang.reflect Field getModifiers

Introduction

In this page you can find the example usage for java.lang.reflect Field getModifiers.

Prototype

public int getModifiers() 

Source Link

Document

Returns the Java language modifiers for the field represented by this Field object, as an integer.

Usage

From source file:org.echocat.redprecursor.annotations.utils.AccessAlsoProtectedMembersReflectivePropertyAccessor.java

@Override
protected Field findField(String name, Class<?> clazz, boolean mustBeStatic) {
    Field result = null;// www. java 2s.  c  o m
    Class<?> current = clazz;
    while (result == null && !Object.class.equals(current)) {
        try {
            final Field potentialField = current.getDeclaredField(name);
            if (!mustBeStatic || Modifier.isStatic(potentialField.getModifiers())) {
                if (!potentialField.isAccessible()) {
                    potentialField.setAccessible(true);
                }
                result = potentialField;
            }
        } catch (NoSuchFieldException ignored) {
        }
        current = current.getSuperclass();
    }
    return result;
}

From source file:fr.mtlx.odm.ClassAssistant.java

public <V> void setProperty(final String propertyName, final T entry, final Collection<V> multipleValues)
        throws MappingException {
    @SuppressWarnings("unchecked")
    Class<T> c = (Class<T>) checkNotNull(entry).getClass();

    final AttributeMetadata meta = metadata.getAttributeMetadata(propertyName);

    if (meta == null) {
        throw new MappingException(format("propertyName: unknown property %s", propertyName));
    }/*  w  w  w  .j  a v  a2  s  .c  o  m*/

    if (!meta.isMultivalued()) {
        throw new MappingException(format("propertyName: single valued property %s", propertyName));
    }

    final Collection<?> targetValues;

    targetValues = buildCollection(meta.getCollectionType(), meta.getObjectType(), multipleValues);

    try {
        PropertyUtils.setProperty(entry, propertyName, targetValues);
    } catch (IllegalAccessException | InvocationTargetException e) {
        throw new MappingException(e);
    } catch (NoSuchMethodException e) {
        try {
            doWithFields(c, (final Field f) -> {
                boolean secured = !f.isAccessible();

                if (secured) {
                    f.setAccessible(true);
                }

                f.set(entry, targetValues);

                if (secured) {
                    f.setAccessible(false);
                }
            }, (final Field field) -> {
                final int modifiers = field.getModifiers();
                return !isStatic(modifiers) && (field.getName() == null ? propertyName == null
                        : field.getName().equals(propertyName));
            });
        } catch (SecurityException | IllegalArgumentException e1) {
            throw new MappingException(e1);
        }
    }
}

From source file:com.glaf.core.util.ReflectUtils.java

public static void setFieldValue(Object target, String fieldName, Object fieldValue) {
    try {//from w  w  w . j  a v a2s.co  m
        Field field = ReflectionUtils.findField(target.getClass(), fieldName);
        if (field != null && !Modifier.isPublic(field.getModifiers())) {
            field.setAccessible(true);
        }
        ReflectionUtils.setField(field, target, fieldValue);
    } catch (Exception ex) {
        try {
            BeanUtils.setProperty(target, fieldName, fieldValue);
        } catch (Exception e) {
        }
    }
}

From source file:com.rosenvold.spring.SpringContextAnalyzer.java

private boolean isFinal(Field field) {
    return Modifier.isFinal(field.getModifiers());
}

From source file:com.cognifide.slice.mapper.GenericSlingMapper.java

/**
 * Returns true if a field can be assigned, i.e. is not final, nor static
 * /*w  w w  .ja v a 2s .  co m*/
 * @param field the field being investigated
 * @return true if the field is assignable, false otherwise
 */
private boolean isFieldAssignable(Field field) {
    int modifiers = field.getModifiers();
    if (Modifier.isFinal(modifiers)) {
        return false;
    } // else

    if (Modifier.isStatic(modifiers)) {
        return false;
    } // else
    return true;
}

From source file:com.rosenvold.spring.SpringContextAnalyzer.java

private boolean isStatic(Field field) {
    return Modifier.isStatic(field.getModifiers());
}

From source file:de.codesourcery.eve.skills.util.SpringBeanInjector.java

private void doInjectDependencies(Object obj)
        throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {

    Class<?> currentClasz = obj.getClass();
    do {//from   w ww.j ava 2 s. c o  m
        // inject fields
        for (Field f : currentClasz.getDeclaredFields()) {

            final int m = f.getModifiers();
            if (Modifier.isStatic(m) || Modifier.isFinal(m)) {
                continue;
            }

            final Resource annot = f.getAnnotation(Resource.class);
            if (annot != null) {
                if (!f.isAccessible()) {
                    f.setAccessible(true);
                }

                if (log.isTraceEnabled()) {
                    log.trace("doInjectDependencies(): Setting field " + f.getName() + " with bean '"
                            + annot.name() + "'");
                }
                f.set(obj, getBean(annot.name()));
            }
        }

        // inject methods
        for (Method method : currentClasz.getDeclaredMethods()) {

            final int m = method.getModifiers();
            if (Modifier.isStatic(m) || Modifier.isAbstract(m)) {
                continue;
            }

            if (method.getParameterTypes().length != 1) {
                continue;
            }

            if (!method.getName().startsWith("set")) {
                continue;
            }

            final Resource annot = method.getAnnotation(Resource.class);
            if (annot != null) {
                if (!method.isAccessible()) {
                    method.setAccessible(true);
                }

                if (log.isTraceEnabled()) {
                    log.trace("doInjectDependencies(): Invoking setter method " + method.getName()
                            + " with bean '" + annot.name() + "'");
                }

                method.invoke(obj, getBean(annot.name()));
            }
        }

        currentClasz = currentClasz.getSuperclass();

    } while (currentClasz != null);
}

From source file:org.testng.spring.test.AbstractDependencyInjectionSpringContextTests.java

private boolean isProtectedInstanceField(Field field) {
    int modifiers = field.getModifiers();
    return !Modifier.isStatic(modifiers) && Modifier.isProtected(modifiers);
}

From source file:py.una.pol.karaku.log.LogPostProcessor.java

/**
 * Revisa todos los mtodos o campos que tengan la anotacin {@link Log} y
 * le asigna el valor el Log del bean en cuestin.
 * /*from   w  w w .  j ava  2 s .c o m*/
 * <br />
 * 
 * {@inheritDoc}
 * 
 * @param bean
 *            bean a procesar
 * @param beanName
 *            nombre del bean
 * @return el mismo bean
 * @throws BeansException
 *             nunca
 */
@Override
public Object postProcessBeforeInitialization(final Object bean, final String beanName) {

    ReflectionUtils.doWithFields(bean.getClass(), new FieldCallback() {

        @Override
        public void doWith(Field field) throws IllegalAccessException {

            if (!Modifier.isFinal(field.getModifiers())) {
                field.setAccessible(true);
                Log log = field.getAnnotation(Log.class);
                field.set(bean, getLogger(bean, log));
            }
        }

    }, new FieldFilter() {

        @Override
        public boolean matches(Field field) {

            return field.getAnnotation(Log.class) != null;
        }
    });

    ReflectionUtils.doWithMethods(bean.getClass(), new MethodCallback() {

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

            Log log = method.getAnnotation(Log.class);
            try {
                method.invoke(bean, getLogger(bean, log));
            } catch (InvocationTargetException e) {
                LOGGER.warn("Error extracting proxy object from {}", bean.getClass().getName(), e);
            }
        }
    }, new MethodFilter() {

        @Override
        public boolean matches(Method method) {

            return method.getAnnotation(Log.class) != null;

        }
    });

    return bean;

}

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  . j  a  va 2  s.  c om
 */
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);
            }
        }
    });
}