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.unovo.frame.utils.SharedPreferencesHelper.java

private static boolean isContSupport(Field field) {
    return (Modifier.isStatic(field.getModifiers()) || Modifier.isFinal(field.getModifiers())
            || Modifier.isAbstract(field.getModifiers()));
}

From source file:org.apache.flink.api.java.Utils.java

private static String getGenericTypeTree(Class<?> type, int indent) {
    String ret = "";
    for (Field field : type.getDeclaredFields()) {
        if (Modifier.isStatic(field.getModifiers()) || Modifier.isTransient(field.getModifiers())) {
            continue;
        }/*from   ww  w  . ja va 2s .  com*/
        ret += StringUtils.repeat(' ', indent) + field.getName() + ":" + field.getType().getName()
                + (field.getType().isEnum() ? " (is enum)" : "") + "\n";
        if (!field.getType().isPrimitive()) {
            ret += getGenericTypeTree(field.getType(), indent + 4);
        }
    }
    return ret;
}

From source file:org.apache.nifi.processors.kafka.pubsub.KafkaProcessorUtils.java

private static Set<String> getPublicStaticStringFieldValues(final Class<?>... classes) {
    final Set<String> strings = new HashSet<>();
    for (final Class<?> classType : classes) {
        for (final Field field : classType.getDeclaredFields()) {
            if (Modifier.isPublic(field.getModifiers()) && Modifier.isStatic(field.getModifiers())
                    && field.getType().equals(String.class)) {
                try {
                    strings.add(String.valueOf(field.get(null)));
                } catch (IllegalArgumentException | IllegalAccessException ex) {
                    //ignore
                }//from   www  .ja  v  a2s .c o  m
            }
        }
    }
    return strings;
}

From source file:com.palantir.ptoss.util.Reflections.java

/**
 * Returns whether or not the given {@link Field} is final.
 *//*from  w w w  .  ja v  a2  s .c  om*/
public static boolean isFieldFinal(Field field) {
    int modifiers = field.getModifiers();
    return Modifier.isFinal(modifiers);
}

From source file:com.palantir.ptoss.util.Reflections.java

/**
 * Returns whether or not the given {@link Field} is static.
 *///  ww w  . j a v a2s. com
public static boolean isFieldStatic(Field field) {
    int modifiers = field.getModifiers();
    return Modifier.isStatic(modifiers);
}

From source file:com.yahoo.egads.data.JsonEncoder.java

public static void fromJson(Object object, JSONObject json_obj) throws Exception {
    // for each json key-value, that has a corresponding variable in object ...
    for (Iterator k = json_obj.keys(); k.hasNext();) {
        String key = (String) k.next();
        Object value = json_obj.get(key);

        // try to access object variable
        Field field = null;
        try {//from w  w  w  . j av  a  2s .com
            field = object.getClass().getField(key);
        } catch (Exception e) {
            continue;
        }
        if (Modifier.isStatic(field.getModifiers())) {
            continue;
        }
        if (Modifier.isPrivate(field.getModifiers())) {
            continue;
        }
        Object member = field.get(object);

        if (json_obj.isNull(key)) {
            field.set(object, null);
            continue;
            // if variable is container... recurse
        } else if (member instanceof JsonAble) {
            ((JsonAble) member).fromJson((JSONObject) value);
            // if variable is an array... recurse on sub-objects
        } else if (member instanceof ArrayList) {
            // Depends on existance of ArrayList<T> template parameter, and T constructor with no arguments.
            // May be better to use custom fromJson() in member class.
            ArrayList memberArray = (ArrayList) member;
            JSONArray jsonArray = (JSONArray) value;

            // find array element constructor
            ParameterizedType arrayType = null;
            if (field.getGenericType() instanceof ParameterizedType) {
                arrayType = (ParameterizedType) field.getGenericType();
            }
            for (Class c = member.getClass(); arrayType == null && c != null; c = c.getSuperclass()) {
                if (c.getGenericSuperclass() instanceof ParameterizedType) {
                    arrayType = (ParameterizedType) c.getGenericSuperclass();
                }
            }
            if (arrayType == null) {
                throw new Exception("could not find ArrayList element type for field 'key'");
            }
            Class elementClass = (Class) (arrayType.getActualTypeArguments()[0]);
            Constructor elementConstructor = elementClass.getConstructor();

            // for each element in JSON array ... append element to member array, recursively decode element
            for (int i = 0; i < jsonArray.length(); ++i) {
                Object element = elementConstructor.newInstance();
                fromJson(element, jsonArray.getJSONObject(i));
                memberArray.add(element);
            }
            // if variable is simple value... set
        } else if (field.getType() == float.class) {
            field.set(object, (float) json_obj.getDouble(key));
        } else {
            field.set(object, value);
        }
    }
}

From source file:org.fusesource.meshkeeper.util.internal.IntrospectionSupport.java

private static void addFields(Object target, Class<?> startClass, Class<?> stopClass,
        LinkedHashMap<String, Object> map) {

    if (startClass != stopClass) {
        addFields(target, startClass.getSuperclass(), stopClass, map);
    }//from   w w w .  j  av  a2s  .  co  m

    Field[] fields = startClass.getDeclaredFields();
    for (int i = 0; i < fields.length; i++) {
        Field field = fields[i];
        if (Modifier.isStatic(field.getModifiers()) || Modifier.isTransient(field.getModifiers())
                || Modifier.isPrivate(field.getModifiers())) {
            continue;
        }

        try {
            field.setAccessible(true);
            Object o = field.get(target);
            if (o != null && o.getClass().isArray()) {
                try {
                    o = Arrays.asList((Object[]) o);
                } catch (Throwable e) {
                }
            }
            map.put(field.getName(), o);
        } catch (Throwable e) {
            e.printStackTrace();
        }
    }

}

From source file:org.apache.atlas.storm.hook.StormTopologyUtil.java

public static Map<String, String> getFieldValues(Object instance, boolean prependClassName,
        Set<Object> objectsToSkip) throws IllegalAccessException {
    if (objectsToSkip == null) {
        objectsToSkip = new HashSet<>();
    }//  w w  w  . j  a va2  s .  com

    Map<String, String> output = new HashMap<>();

    try {
        if (objectsToSkip.add(instance)) {
            Class clazz = instance.getClass();
            for (Class<?> c = clazz; c != null; c = c.getSuperclass()) {
                Field[] fields = c.getDeclaredFields();
                for (Field field : fields) {
                    if (java.lang.reflect.Modifier.isStatic(field.getModifiers())) {
                        continue;
                    }

                    String key;
                    if (prependClassName) {
                        key = String.format("%s.%s", clazz.getSimpleName(), field.getName());
                    } else {
                        key = field.getName();
                    }

                    boolean accessible = field.isAccessible();
                    if (!accessible) {
                        field.setAccessible(true);
                    }
                    Object fieldVal = field.get(instance);
                    if (fieldVal == null) {
                        continue;
                    } else if (fieldVal.getClass().isPrimitive() || isWrapperType(fieldVal.getClass())) {
                        if (toString(fieldVal, false).isEmpty())
                            continue;
                        output.put(key, toString(fieldVal, false));
                    } else if (isMapType(fieldVal.getClass())) {
                        //TODO: check if it makes more sense to just stick to json
                        // like structure instead of a flatten output.
                        Map map = (Map) fieldVal;
                        for (Object entry : map.entrySet()) {
                            Object mapKey = ((Map.Entry) entry).getKey();
                            Object mapVal = ((Map.Entry) entry).getValue();

                            String keyStr = getString(mapKey, false, objectsToSkip);
                            String valStr = getString(mapVal, false, objectsToSkip);
                            if (StringUtils.isNotEmpty(valStr)) {
                                output.put(String.format("%s.%s", key, keyStr), valStr);
                            }
                        }
                    } else if (isCollectionType(fieldVal.getClass())) {
                        //TODO check if it makes more sense to just stick to
                        // json like structure instead of a flatten output.
                        Collection collection = (Collection) fieldVal;
                        if (collection.size() == 0)
                            continue;
                        String outStr = "";
                        for (Object o : collection) {
                            outStr += getString(o, false, objectsToSkip) + ",";
                        }
                        if (outStr.length() > 0) {
                            outStr = outStr.substring(0, outStr.length() - 1);
                        }
                        output.put(key, String.format("%s", outStr));
                    } else {
                        Map<String, String> nestedFieldValues = getFieldValues(fieldVal, false, objectsToSkip);
                        for (Map.Entry<String, String> entry : nestedFieldValues.entrySet()) {
                            output.put(String.format("%s.%s", key, entry.getKey()), entry.getValue());
                        }
                    }
                    if (!accessible) {
                        field.setAccessible(false);
                    }
                }
            }
        }
    } catch (Exception e) {
        LOG.warn("Exception while constructing topology", e);
    }
    return output;
}

From source file:gov.va.vinci.leo.tools.LeoUtils.java

/**
 * Create the set of ConfigurationParameter objects from the Param class of an object.
 *
 * @param c Param class//from   w  w  w. j  a  v  a  2s .  co  m
 * @return Set of ConfigurationParameter objects
 */
public static Set<ConfigurationParameter> getStaticConfigurationParameters(Class c) {
    Set<ConfigurationParameter> list = new HashSet<ConfigurationParameter>();
    Field[] fields = c.getFields();
    for (Field field : fields) {
        try {
            if (field.getType().equals(ConfigurationParameter.class)
                    && Modifier.isStatic(field.getModifiers())) {
                list.add((ConfigurationParameter) field.get(null));
            }
        } catch (IllegalAccessException e) {
            // Handle exception here
        }
    }
    return list;
}

From source file:org.apache.atlas.repository.graph.TitanGraphProvider.java

/**
 * Titan loads index backend name to implementation using StandardIndexProvider.ALL_MANAGER_CLASSES
 * But StandardIndexProvider.ALL_MANAGER_CLASSES is a private static final ImmutableMap
 * Only way to inject Solr5Index is to modify this field. So, using hacky reflection to add Sol5Index
 *//*  ww  w .  j  av  a 2 s.  c om*/
private static void addSolr5Index() {
    try {
        Field field = StandardIndexProvider.class.getDeclaredField("ALL_MANAGER_CLASSES");
        field.setAccessible(true);

        Field modifiersField = Field.class.getDeclaredField("modifiers");
        modifiersField.setAccessible(true);
        modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);

        Map<String, String> customMap = new HashMap(StandardIndexProvider.getAllProviderClasses());
        customMap.put("solr5", Solr5Index.class.getName());
        ImmutableMap<String, String> immap = ImmutableMap.copyOf(customMap);
        field.set(null, immap);

        LOG.debug("Injected solr5 index - {}", Solr5Index.class.getName());
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}