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:com.alibaba.dubbo.config.spring.beans.factory.annotation.ReferenceAnnotationBeanPostProcessor.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  w  ww . j ava  2s .co  m
 */
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 {

            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:com.nonninz.robomodel.RoboModel.java

List<Field> getSavedFields() { //TODO: cache results
    final List<Field> savedFields = new ArrayList<Field>();

    final Field[] declaredFields = getClass().getDeclaredFields();
    boolean saved;
    for (final Field field : declaredFields) {

        saved = false;//from w  ww.  ja  v a2 s  .c om
        saved = saved || field.isAnnotationPresent(Save.class); // If @Save is present, save it
        saved = saved || Modifier.isPublic(field.getModifiers()); // If it is public, save it
        saved = saved && !Modifier.isStatic(field.getModifiers()); // If it is static, don't save it
        saved = saved && !field.isAnnotationPresent(Exclude.class); // If @Exclude, don't save it

        if (saved) {
            savedFields.add(field);
        }
    }

    return savedFields;
}

From source file:de.micromata.genome.util.strings.ReducedReflectionToStringBuilder.java

@Override
protected boolean accept(Field field) {
    // if (field.getName().indexOf(ClassUtils.INNER_CLASS_SEPARATOR_CHAR) != -1) {
    // // Reject field from inner class.
    // return false;
    // }/* w  w  w  . ja  v a2  s.com*/
    if (field.getAnnotation(NoStringifyAnnotation.class) != null) {
        return false;
    }
    if (Modifier.isTransient(field.getModifiers()) && !this.isAppendTransients()) {
        // transients.
        return false;
    }
    if (Modifier.isStatic(field.getModifiers()) && !this.isAppendStatics()) {
        // transients.
        return false;
    }
    return true;
}

From source file:adalid.core.Tab.java

private void finaliseFields() {
    String name;//from   w ww.j  a  v  a2  s .co m
    Class<?> type;
    int modifiers;
    boolean restricted;
    Object o;
    int depth = depth();
    int round = round();
    for (Field field : XS1.getFields(getClass(), Tab.class)) { // getClass().getDeclaredFields()
        field.setAccessible(true);
        logger.trace(field);
        name = field.getName();
        type = field.getType();
        if (!TabField.class.isAssignableFrom(type)) {
            continue;
        }
        modifiers = field.getModifiers();
        restricted = Modifier.isStatic(modifiers) || Modifier.isFinal(modifiers);
        if (restricted) {
            continue;
        }
        String errmsg = "failed to initialize field \"" + field + "\" at " + this;
        try {
            o = field.get(this);
            if (o == null) {
                logger.debug(message(type, name, o, depth, round));
            } else if (o instanceof TabField) {
                finaliseTabField(field, (TabField) o);
            }
        } catch (IllegalArgumentException | IllegalAccessException ex) {
            logger.error(errmsg, ThrowableUtils.getCause(ex));
            TLC.getProject().getParser().increaseErrorCount();
        }
    }
}

From source file:net.stickycode.mockwire.spring30.MockwireFieldInjectionAnnotationBeanPostProcessor.java

private InjectionMetadata buildAutowiringMetadata(Class clazz) {
    LinkedList<InjectionMetadata.InjectedElement> elements = new LinkedList<InjectionMetadata.InjectedElement>();
    Class<?> targetClass = clazz;

    do {/*from   w w  w  .j a  v  a  2 s.c o  m*/
        LinkedList<InjectionMetadata.InjectedElement> currElements = new LinkedList<InjectionMetadata.InjectedElement>();
        for (Field field : targetClass.getDeclaredFields()) {
            Annotation annotation = findAutowiredAnnotation(field);
            if (annotation != null) {
                if (Modifier.isStatic(field.getModifiers())) {
                    if (logger.isWarnEnabled()) {
                        logger.warn("Autowired annotation is not supported on static fields: " + field);
                    }
                    continue;
                }
                boolean required = determineRequiredStatus(annotation);
                currElements.add(new AutowiredFieldElement(field, required));
            }
        }
        elements.addAll(0, currElements);
        targetClass = targetClass.getSuperclass();
    } while (targetClass != null && targetClass != Object.class);

    return new InjectionMetadata(clazz, elements);
}

From source file:adalid.core.Key.java

private void finaliseFields() {
    String name;//  ww  w .  j av a  2  s .  c o  m
    Class<?> type;
    int modifiers;
    boolean restricted;
    Object o;
    int depth = depth();
    int round = round();
    for (Field field : XS1.getFields(getClass(), Key.class)) { // getClass().getDeclaredFields()
        field.setAccessible(true);
        logger.trace(field);
        name = field.getName();
        type = field.getType();
        if (!KeyField.class.isAssignableFrom(type)) {
            continue;
        }
        modifiers = field.getModifiers();
        restricted = Modifier.isStatic(modifiers) || Modifier.isFinal(modifiers);
        if (restricted) {
            continue;
        }
        String errmsg = "failed to initialize field \"" + field + "\" at " + this;
        try {
            o = field.get(this);
            if (o == null) {
                logger.debug(message(type, name, o, depth, round));
            } else if (o instanceof KeyField) {
                finaliseKeyField(field, (KeyField) o);
            }
        } catch (IllegalArgumentException | IllegalAccessException ex) {
            logger.error(errmsg, ThrowableUtils.getCause(ex));
            TLC.getProject().getParser().increaseErrorCount();
        }
    }
}

From source file:com.tongbanjie.tarzan.rpc.protocol.RpcCommand.java

private void customHeaderToMap() throws RpcCommandException {
    if (this.customHeader != null) {
        Field[] fields = getClazzFields(customHeader.getClass());
        if (null == this.customFields) {
            this.customFields = new HashMap<String, String>(8);
        }/*from  ww w  .j  av a2s  .c o  m*/
        for (Field field : fields) {
            String fieldName = field.getName();
            Class clazz = field.getType();
            if (Modifier.isStatic(field.getModifiers()) || fieldName.startsWith("this")) {
                continue;
            }
            Object value;
            try {
                field.setAccessible(true);
                value = field.get(this.customHeader);
            } catch (Exception e) {
                throw new RpcCommandException(
                        "Encode the header failed, get the value of field <" + fieldName + "> error.", e);
            }
            if (value == null) {
                continue;
            }
            if (clazz.isEnum()) {
                this.customFields.put(fieldName, value.toString());
            } else {
                String type = getCanonicalName(clazz);
                String strValue = ClassUtils.simpleValueToString(type, value);
                if (strValue == null) {
                    throw new RpcCommandException("Encode the header failed, the field <" + fieldName
                            + "> type <" + getCanonicalName(clazz) + "> is not supported.");
                }
                this.customFields.put(fieldName, strValue);
            }
        }
    }
}

From source file:com.wingnest.play2.origami.plugin.OrigamiPlugin.java

@SuppressWarnings("unchecked")
private void maintainProperties(final OClass oClass, final Class<?> javaClass) {
    final Map<String, Map<String, Object>> compositeIndexMap = new HashMap<String, Map<String, Object>>();
    final Map<String, OIndex<?>> classIndexCache = new HashMap<String, OIndex<?>>();
    final Map<String, OIndex<?>> compositeIndexCache = new HashMap<String, OIndex<?>>();
    final Set<String> wkCurIndexNames = new HashSet<String>();
    //      for ( final OProperty prop : oClass.properties() ) {
    //         debug("[b] prop name =%s, type = %s", prop.getName(), prop.getType());
    //      }/* w w w. j  a va2s .  com*/
    for (final OIndex<?> index : oClass.getClassIndexes()) {
        wkCurIndexNames.add(index.getName());
        if (index.getName().indexOf('.') > -1) {
            classIndexCache.put(index.getName(), index);
        } else {
            compositeIndexCache.put(index.getName(), index);
        }
        //         debug("[b] index name =%s, type = %s", index.getName(), index.getType());
    }
    for (final Field field : javaClass.getDeclaredFields()) {
        if (Modifier.isStatic(field.getModifiers()) || field.isAnnotationPresent(Id.class)
                || field.isAnnotationPresent(Version.class) || field.isAnnotationPresent(Transient.class)
                || field.isAnnotationPresent(DisupdateFlag.class))
            continue;

        OProperty prop = oClass.getProperty(field.getName());
        final OType type = guessType(field);
        if (prop == null) {
            if (type != null) {
                debug("create property : %s", field.getName());
                prop = oClass.createProperty(field.getName(), type);
            }
        } else {
            if (!type.equals(prop.getType())) {
                deleteIndex(oClass, oClass.getName() + "." + field.getName(), classIndexCache,
                        compositeIndexCache);
                debug("drop property : %s", field.getName());
                oClass.dropProperty(field.getName());
                debug("create property : %s", field.getName());
                prop = oClass.createProperty(field.getName(), type);
            }
        }
        final Index index = field.getAnnotation(Index.class);
        if (index != null) {
            final String indexName = makeIndexName(javaClass, field);
            OIndex<?> oindex = classIndexCache.get(indexName);
            if (oindex == null) {
                debug("create Class Index : %s.%s", javaClass.getSimpleName(), field.getName());
                if (prop != null) {
                    oindex = oClass.createIndex(indexName, index.indexType(), field.getName());
                } else {
                    error("could not create Class Index : property(%s.%s) has't type", javaClass.getName(),
                            field.getName());
                }
            }
            if (oindex != null) {
                wkCurIndexNames.remove(oindex.getName());
            }
        }
        final CompositeIndex cindex = field.getAnnotation(CompositeIndex.class);
        if (cindex != null) {
            final String indexName = javaClass.getSimpleName() + "_" + cindex.indexName();
            Map<String, Object> ci = compositeIndexMap.get(indexName);
            if (ci == null) {
                ci = new HashMap<String, Object>();
                ci.put("fields", new HashSet<Field>());
                ci.put("indexType", OClass.INDEX_TYPE.UNIQUE);
            }
            if (!cindex.indexType().equals(OClass.INDEX_TYPE.UNIQUE))
                ci.put("indexType", cindex.indexType());
            ((Set<Field>) ci.get("fields")).add(field);
            compositeIndexMap.put(indexName, ci);
        }
    }

    for (final String cindexName : compositeIndexMap.keySet()) {
        final Map<String, Object> ci = compositeIndexMap.get(cindexName);
        final Set<Field> fields = (Set<Field>) ci.get("fields");
        final String[] fieldNames = new String[fields.size()];
        int i = 0;
        for (final Field f : fields) {
            fieldNames[i++] = f.getName();
        }
        final OIndex<?> oindex = compositeIndexCache.get(cindexName);
        if (oindex != null && !CollectionUtils.isEqualCollection(Arrays.asList(fieldNames),
                oindex.getDefinition().getFields())) {
            debug("recreate composite index : %s", cindexName);
            deleteIndex(oClass, cindexName, classIndexCache, compositeIndexCache);
        } else if (oindex == null) {
            debug("create composite index : %s", cindexName);
        }
        oClass.createIndex(cindexName, (OClass.INDEX_TYPE) ci.get("indexType"), fieldNames);
        wkCurIndexNames.remove(cindexName);
    }

    for (final String indexName : wkCurIndexNames) {
        final int ind = indexName.indexOf('.');
        if (ind > -1) {
            debug("delete index : %s", indexName);
        } else {
            debug("delete composite index : %s", indexName);
        }
        deleteIndex(oClass, indexName, classIndexCache, compositeIndexCache);
    }

    //      for ( final OProperty prop : oClass.properties() ) {
    //         debug("[a] prop name =%s, type = %s", prop.getName(), prop.getType());
    //      }
    //      for ( final OIndex<?> index : oClass.getClassIndexes() ) {
    //         debug("[a] class index name =%s, type = %s", index.getName(), index.getType());
    //      }
}

From source file:org.bitpipeline.lib.friendlyjson.JSONEntity.java

/** Des-serialize a JSON object.
 * @throws JSONException//from  w w  w.ja  v a  2 s.  c  o  m
 * @throws JSONMappingException */
public JSONEntity(JSONObject json) throws JSONMappingException {
    if (json == null)
        return;
    Class<?> clazz = this.getClass();
    List<Field> declaredFields = new ArrayList<Field>();
    do {
        Field[] fields = clazz.getDeclaredFields();
        declaredFields.addAll(Arrays.asList(fields));
        clazz = clazz.getSuperclass();
    } while (clazz != null && !clazz.isAssignableFrom(JSONEntity.class));
    for (Field field : declaredFields) {
        if ((field.getModifiers() & Modifier.TRANSIENT) != 0) { // don't care about transient fields.
            continue;
        }

        String fieldName = field.getName();
        if (fieldName.equals("this$0"))
            continue;

        boolean accessible = field.isAccessible();
        if (!accessible)
            field.setAccessible(true);

        Class<?> type = field.getType();

        if (type.isArray()) {
            Class<?> componentClass = type.getComponentType();
            JSONArray jsonArray = null;
            try {
                jsonArray = json.getJSONArray(fieldName);
            } catch (JSONException e) {
                // no data for this field found.
                continue;
            }

            int size = jsonArray.length();

            Object array = Array.newInstance(componentClass, size);
            for (int i = 0; i < size; i++) {
                try {
                    Object item = fromJson(componentClass, jsonArray.get(i));
                    Array.set(array, i, item);
                } catch (Exception e) {
                    System.err.println("Invalid array component for class " + this.getClass().getName()
                            + " field " + field.getName() + "::" + field.getType().getName());
                }
            }

            try {
                field.set(this, array);
            } catch (Exception e) {
                throw new JSONMappingException(e);
            }
        } else if (JSONEntity.class.isAssignableFrom(type)) {
            try {
                Object entity = readJSONEntity(type, json.getJSONObject(fieldName));
                field.set(this, entity);
            } catch (JSONException e) {
                // keep going.. the json representation doesn't have value for this field.
            } catch (Exception e) {
                throw new JSONMappingException(e);
            }
        } else {
            FieldSetter setter = JSON_READERS.get(type.getName());
            if (setter != null) {
                try {
                    setter.setField(this, field, json, fieldName);
                } catch (JSONException e) {
                    // do nothing. We just didn't receive data for this field
                } catch (Exception e) {
                    throw new JSONMappingException(e);
                }
            } else {
                Object jsonObj;
                try {
                    jsonObj = json.get(fieldName);
                } catch (Exception e) {
                    jsonObj = null;
                }
                if (jsonObj != null) {
                    Object value = fromJson(type, jsonObj);
                    try {
                        field.set(this, value);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else {
                    System.err.println("No setter for " + field);
                }

            }
        }

        if (!accessible)
            field.setAccessible(false);
    }
}

From source file:com.tongbanjie.tarzan.rpc.protocol.RpcCommand.java

public CustomHeader decodeCustomHeader(Class<? extends CustomHeader> classHeader) throws RpcCommandException {
    CustomHeader objectHeader;/* w  w w.ja  v  a  2  s  .com*/
    try {
        objectHeader = classHeader.newInstance();
    } catch (InstantiationException e) {
        return null;
    } catch (IllegalAccessException e) {
        return null;
    }
    if (MapUtils.isNotEmpty(this.customFields)) {
        Field[] fields = getClazzFields(classHeader);
        for (Field field : fields) {
            String fieldName = field.getName();
            Class clazz = field.getType();
            if (Modifier.isStatic(field.getModifiers()) || fieldName.startsWith("this")) {
                continue;
            }
            String value = this.customFields.get(fieldName);
            if (value == null) {
                continue;
            }
            field.setAccessible(true);
            Object valueParsed;
            if (clazz.isEnum()) {
                valueParsed = Enum.valueOf(clazz, value);
            } else {
                String type = getCanonicalName(clazz);
                try {
                    valueParsed = ClassUtils.parseSimpleValue(type, value);
                } catch (ParseException e) {
                    throw new RpcCommandException("Encode the header failed, the custom field <" + fieldName
                            + "> type <" + getCanonicalName(clazz) + "> parse error:" + e.getMessage());
                }
            }
            if (valueParsed == null) {
                throw new RpcCommandException("Encode the header failed, the custom field <" + fieldName
                        + "> type <" + getCanonicalName(clazz) + "> is not supported.");
            }
            try {
                field.set(objectHeader, valueParsed);
            } catch (IllegalAccessException e) {
                throw new RpcCommandException(
                        "Encode the header failed, set the value of field < " + fieldName + "> error.", e);
            }
        }

        objectHeader.checkFields();
    }

    return objectHeader;
}