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:au.com.dw.testdatacapturej.reflection.MetadataGenerationHandler.java

/**
 * Use reflection to process the fields in an object. Iterates through the fields in the object
 * and passes them to the appropriate handlers.
 * //from  w w  w . j  a v a2s.c  om
 * Note: does not handle static fields yet.
 * 
 * @param object
 * @throws IllegalArgumentException
 * @throws IllegalAccessException
 */
protected void handleFields(ObjectInfo info) throws IllegalArgumentException, IllegalAccessException {

    // use reflection to get the fields of the class
    Object object = info.getValue();
    Class<?> clazz = object.getClass();
    Field[] fields = clazz.getDeclaredFields();
    AccessibleObject.setAccessible(fields, true);

    // check configuration for non-standard handling
    ConfigUtil configUtil = new ConfigUtil();

    // get list of field names that have been configured to have non-standard setter method generation
    List<String> ignoredSetterFieldNames = configUtil.getIgnoredSetters(info);

    // get list of collection field names for collection that are only accessed through adder methods
    List<CollectionAdderConfig> collectionConfigs = configUtil.getAddedCollections(info);

    for (int i = 0; i < fields.length; i++) {
        Field field = fields[i];

        int mod = field.getModifiers();

        // ignore static fields
        if (!Modifier.isStatic(mod)) {
            // get the field info
            String fieldName = field.getName();
            Object fieldValue = field.get(object);

            // create new ObjectInfo for the field object
            ObjectInfo fieldInfo = new ObjectInfo();
            fieldInfo.setFieldName(fieldName);
            fieldInfo.setValue(fieldValue);
            fieldInfo.setContainingClassFieldName(info.getClassFieldName());
            fieldInfo.getConstructorInfo().setHasDefaultConstructor(hasDefaultConstructor(fieldValue));

            // check if requires any special setter method generation
            if (ignoredSetterFieldNames != null) {
                if (ignoredSetterFieldNames.contains(fieldName)) {
                    fieldInfo.getSetterAdderInfo().setSetterGenerationType(SetterGenerationType.IGNORE);
                }
            }

            // determine type of field and pass to handler
            if (fieldValue != null) {
                if (!ReflectionUtil.hasSetterMethod(object, fieldName, fieldValue)) {
                    fieldInfo.getSetterAdderInfo().setHasSetter(false);
                }

                if (TypeUtil.isJavaClass(fieldValue)) {
                    fieldInfo.setType(ObjectType.SIMPLE);

                    fieldInfo.setClassName(fieldValue.getClass().getName());
                    fieldInfo.setClassFieldName(BuilderUtil.createClassFieldName(fieldValue, null, null));
                } else if (TypeUtil.isArray(fieldValue)) {
                    fieldInfo.setType(ObjectType.ARRAY);

                    // special handling for array class names
                    fieldInfo.setClassName(ReflectionUtil.getArrayClassName(fieldValue));
                    String arrayType = fieldValue.getClass().getComponentType().getName();
                    fieldInfo.setClassFieldName(BuilderUtil.createArrayClassFieldName(arrayType, null, null));

                    if (!fieldInfo.isSetterIgnoreType()) {
                        handleArray(fieldInfo);
                    }
                } else if (TypeUtil.isCollection(fieldValue)) {
                    fieldInfo.setType(ObjectType.COLLECTION);

                    fieldInfo.setClassName(fieldValue.getClass().getName());
                    fieldInfo.setClassFieldName(BuilderUtil.createClassFieldName(fieldValue, null, null));

                    // check if the collection field is only accessed through adder methods
                    // Note: the adder check overrides the ignored setter check if both are set
                    CollectionAdderConfig foundConfig = configUtil.getCollectionAdderConfig(collectionConfigs,
                            fieldName);

                    if (foundConfig != null) {
                        fieldInfo.getSetterAdderInfo().setUsesAdder(true);
                        fieldInfo.getSetterAdderInfo().setAdderMethodName(foundConfig.getAdderMethodName());

                        handleCollection(fieldInfo);
                    } else if (!fieldInfo.isSetterIgnoreType()) {
                        handleCollection(fieldInfo);
                    }
                } else if (TypeUtil.isMap(fieldValue)) {
                    fieldInfo.setType(ObjectType.MAP);

                    fieldInfo.setClassName(fieldValue.getClass().getName());
                    fieldInfo.setClassFieldName(BuilderUtil.createClassFieldName(fieldValue, null, null));

                    if (!fieldInfo.isSetterIgnoreType()) {
                        handleMap(fieldInfo);
                    }
                } else {
                    fieldInfo.setType(ObjectType.OBJECT);

                    fieldInfo.setClassName(fieldValue.getClass().getName());
                    fieldInfo.setClassFieldName(BuilderUtil.createClassFieldName(fieldValue, null, null));

                    if (!fieldInfo.isSetterIgnoreType()) {
                        handleFields(fieldInfo);
                    }
                }
            } else {
                // get class name from the Field if the field value is null
                fieldInfo.setClassName(ReflectionUtil.getClassNameFromField(field));
                fieldInfo.setClassFieldName(BuilderUtil.createClassFieldName(field, null, null));

                fieldInfo.setType(ObjectType.SIMPLE);
            }

            // check if configured parameterized constructor is to be used for the field
            fieldInfo.getConstructorInfo()
                    .addConstructorParamFieldNames(configUtil.getConstructionParameters(fieldInfo));

            // add the parent class to field class link
            fieldInfo.setParentInfo(info);
            info.addFieldToList(fieldInfo);
        }
    }
}

From source file:org.apache.dubbo.config.spring.beans.factory.annotation.CompatibleReferenceAnnotationBeanPostProcessor.java

/**
 * Finds {@link InjectionMetadata.InjectedElement} Metadata from annotated {@link Reference @Reference} fields
 *
 * @param beanClass The {@link Class} of Bean
 * @return non-null {@link List}/*from  ww w.j  a  va 2s .co m*/
 */
private List<ReferenceFieldElement> findFieldReferenceMetadata(final Class<?> beanClass) {

    final List<ReferenceFieldElement> elements = new LinkedList<ReferenceFieldElement>();

    ReflectionUtils.doWithFields(beanClass, new ReflectionUtils.FieldCallback() {
        @Override
        public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException {

            Reference reference = getAnnotation(field, Reference.class);

            if (reference != null) {

                if (Modifier.isStatic(field.getModifiers())) {
                    if (logger.isWarnEnabled()) {
                        logger.warn("@Reference annotation is not supported on static fields: " + field);
                    }
                    return;
                }

                elements.add(new ReferenceFieldElement(field, reference));
            }

        }
    });

    return elements;

}

From source file:org.castor.jaxb.reflection.ClassInfoBuilder.java

/**
 * Checks if a field of a class is describeable or not e.g. static or
 * transient fields are not described./*  w  w w .  j av  a  2s .c  o  m*/
 * 
 * @param type
 *            the Class holding the field
 * @param field
 *            the field to check
 * @return true if the field should be described
 */
private boolean isDescribeable(final Class<?> type, final Field field) {
    boolean isDescribeable = true;
    Class<?> declaringClass = field.getDeclaringClass();
    if ((declaringClass != null) && !type.equals(declaringClass) && (!declaringClass.isInterface())) {
        isDescribeable = false;
    }
    if (Modifier.isStatic(field.getModifiers())) {
        isDescribeable &= false;
    }
    if (Modifier.isTransient(field.getModifiers())) {
        isDescribeable &= false;
    }
    if (field.isSynthetic()) {
        isDescribeable &= false;
    }
    return isDescribeable;
}

From source file:com.haulmont.cuba.core.app.serialization.EntitySerialization.java

protected void makeFieldAccessible(Field field) {
    if (field != null && !Modifier.isPublic(field.getModifiers())) {
        field.setAccessible(true);/* w  w  w.  j a  va2  s  .  com*/
    }
}

From source file:com.alibaba.otter.shared.common.model.config.pipeline.PipelineParameter.java

/**
 * ?pipeline?/*  w  w w. ja va2  s  . c  o m*/
 */
public void merge(PipelineParameter pipelineParameter) {
    try {
        Field[] fields = this.getClass().getDeclaredFields();
        for (int i = 0; i < fields.length; i++) {
            Field field = fields[i];
            // Skip static and final fields.
            if (Modifier.isStatic(field.getModifiers()) || Modifier.isFinal(field.getModifiers())) {
                continue;
            }

            ReflectionUtils.makeAccessible(field);
            Object srcValue = field.get(pipelineParameter);
            if (srcValue != null) { // null
                field.set(this, srcValue);
            }
        }
    } catch (Exception e) {
        // ignore
    }
}

From source file:de.javakaffee.web.msm.serializer.javolution.AaltoTranscoderTest.java

private void assertEqualDeclaredFields(final Class<? extends Object> clazz, final Object one,
        final Object another) throws Exception, IllegalAccessException {
    for (final Field field : clazz.getDeclaredFields()) {
        field.setAccessible(true);/*from   www . j  a  v  a 2  s .  com*/
        if (!Modifier.isTransient(field.getModifiers())) {
            assertDeepEquals(field.get(one), field.get(another));
        }
    }
}

From source file:de.javakaffee.web.msm.serializer.javolution.JavolutionTranscoderTest.java

private void assertEqualDeclaredFields(final Class<? extends Object> clazz, final Object one,
        final Object another, final Map<Object, Object> alreadyChecked)
        throws Exception, IllegalAccessException {
    for (final Field field : clazz.getDeclaredFields()) {
        field.setAccessible(true);//w w w.  j av a2  s.  com
        if (!Modifier.isTransient(field.getModifiers())) {
            assertDeepEquals(field.get(one), field.get(another), alreadyChecked);
        }
    }
}

From source file:com.googlecode.android_scripting.facade.AndroidFacade.java

@Rpc(description = "Get list of constants (static final fields) for a class")
public Bundle getConstants(
        @RpcParameter(name = "classname", description = "Class to get constants from") String classname)
        throws Exception {
    Bundle result = new Bundle();
    int flags = Modifier.FINAL | Modifier.PUBLIC | Modifier.STATIC;
    Class<?> clazz = Class.forName(classname);
    for (Field field : clazz.getFields()) {
        if ((field.getModifiers() & flags) == flags) {
            Class<?> type = field.getType();
            String name = field.getName();
            if (type == int.class) {
                result.putInt(name, field.getInt(null));
            } else if (type == long.class) {
                result.putLong(name, field.getLong(null));
            } else if (type == double.class) {
                result.putDouble(name, field.getDouble(null));
            } else if (type == char.class) {
                result.putChar(name, field.getChar(null));
            } else if (type instanceof Object) {
                result.putString(name, field.get(null).toString());
            }/*from w  w  w. j av  a2s  .  co  m*/
        }
    }
    return result;
}

From source file:com.p5solutions.core.utils.ReflectionUtility.java

/**
 * Checks if is static./* w  ww  .  j  a  v a 2 s .c om*/
 * 
 * @param field
 *          the field
 * @return true, if is static
 */
public static boolean isStatic(Field field) {
    int modifiers = field.getModifiers();
    return Modifier.isStatic(modifiers);
}

From source file:com.p5solutions.core.utils.ReflectionUtility.java

/**
 * Checks if is final./*from   ww w .  ja  va  2  s  .c  om*/
 * 
 * @param field
 *          the field
 * @return true, if is final
 */
public static boolean isFinal(Field field) {
    int modifiers = field.getModifiers();
    return Modifier.isFinal(modifiers);
}