Example usage for java.lang.reflect Field get

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

Introduction

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

Prototype

@CallerSensitive
@ForceInline 
public Object get(Object obj) throws IllegalArgumentException, IllegalAccessException 

Source Link

Document

Returns the value of the field represented by this Field , on the specified object.

Usage

From source file:com.hurence.logisland.util.string.StringUtilsTest.java

/**
 * Sets an environment variable FOR THE CURRENT RUN OF THE JVM
 * Does not actually modify the system's environment variables,
 *  but rather only the copy of the variables that java has taken,
 *  and hence should only be used for testing purposes!
 * @param key The Name of the variable to set
 * @param value The value of the variable to set
 *//*from  ww w.  ja  v  a 2s.c  o  m*/
@SuppressWarnings("unchecked")
public static <K, V> void setEnv(final String key, final String value) throws InvocationTargetException {
    try {
        /// we obtain the actual environment
        final Class<?> processEnvironmentClass = Class.forName("java.lang.ProcessEnvironment");
        final Field theEnvironmentField = processEnvironmentClass.getDeclaredField("theEnvironment");
        final boolean environmentAccessibility = theEnvironmentField.isAccessible();
        theEnvironmentField.setAccessible(true);

        final Map<K, V> env = (Map<K, V>) theEnvironmentField.get(null);

        if (SystemUtils.IS_OS_WINDOWS) {
            // This is all that is needed on windows running java jdk 1.8.0_92
            if (value == null) {
                env.remove(key);
            } else {
                env.put((K) key, (V) value);
            }
        } else {
            // This is triggered to work on openjdk 1.8.0_91
            // The ProcessEnvironment$Variable is the key of the map
            final Class<K> variableClass = (Class<K>) Class.forName("java.lang.ProcessEnvironment$Variable");
            final Method convertToVariable = variableClass.getMethod("valueOf", String.class);
            final boolean conversionVariableAccessibility = convertToVariable.isAccessible();
            convertToVariable.setAccessible(true);

            // The ProcessEnvironment$Value is the value fo the map
            final Class<V> valueClass = (Class<V>) Class.forName("java.lang.ProcessEnvironment$Value");
            final Method convertToValue = valueClass.getMethod("valueOf", String.class);
            final boolean conversionValueAccessibility = convertToValue.isAccessible();
            convertToValue.setAccessible(true);

            if (value == null) {
                env.remove(convertToVariable.invoke(null, key));
            } else {
                // we place the new value inside the map after conversion so as to
                // avoid class cast exceptions when rerunning this code
                env.put((K) convertToVariable.invoke(null, key), (V) convertToValue.invoke(null, value));

                // reset accessibility to what they were
                convertToValue.setAccessible(conversionValueAccessibility);
                convertToVariable.setAccessible(conversionVariableAccessibility);
            }
        }
        // reset environment accessibility
        theEnvironmentField.setAccessible(environmentAccessibility);

        // we apply the same to the case insensitive environment
        final Field theCaseInsensitiveEnvironmentField = processEnvironmentClass
                .getDeclaredField("theCaseInsensitiveEnvironment");
        final boolean insensitiveAccessibility = theCaseInsensitiveEnvironmentField.isAccessible();
        theCaseInsensitiveEnvironmentField.setAccessible(true);
        // Not entirely sure if this needs to be casted to ProcessEnvironment$Variable and $Value as well
        final Map<String, String> cienv = (Map<String, String>) theCaseInsensitiveEnvironmentField.get(null);
        if (value == null) {
            // remove if null
            cienv.remove(key);
        } else {
            cienv.put(key, value);
        }
        theCaseInsensitiveEnvironmentField.setAccessible(insensitiveAccessibility);
    } catch (final ClassNotFoundException | NoSuchMethodException | IllegalAccessException
            | InvocationTargetException e) {
        throw new IllegalStateException("Failed setting environment variable <" + key + "> to <" + value + ">",
                e);
    } catch (final NoSuchFieldException e) {
        // we could not find theEnvironment
        final Map<String, String> env = System.getenv();
        Stream.of(Collections.class.getDeclaredClasses())
                // obtain the declared classes of type $UnmodifiableMap
                .filter(c1 -> "java.util.Collections$UnmodifiableMap".equals(c1.getName())).map(c1 -> {
                    try {
                        return c1.getDeclaredField("m");
                    } catch (final NoSuchFieldException e1) {
                        throw new IllegalStateException("Failed setting environment variable <" + key + "> to <"
                                + value + "> when locating in-class memory map of environment", e1);
                    }
                }).forEach(field -> {
                    try {
                        final boolean fieldAccessibility = field.isAccessible();
                        field.setAccessible(true);
                        // we obtain the environment
                        final Map<String, String> map = (Map<String, String>) field.get(env);
                        if (value == null) {
                            // remove if null
                            map.remove(key);
                        } else {
                            map.put(key, value);
                        }
                        // reset accessibility
                        field.setAccessible(fieldAccessibility);
                    } catch (final ConcurrentModificationException e1) {
                        // This may happen if we keep backups of the environment before calling this method
                        // as the map that we kept as a backup may be picked up inside this block.
                        // So we simply skip this attempt and continue adjusting the other maps
                        // To avoid this one should always keep individual keys/value backups not the entire map
                        System.out.println("Attempted to modify source map: " + field.getDeclaringClass() + "#"
                                + field.getName() + e1);
                    } catch (final IllegalAccessException e1) {
                        throw new IllegalStateException("Failed setting environment variable <" + key + "> to <"
                                + value + ">. Unable to access field!", e1);
                    }
                });
    }
    System.out.println(
            "Set environment variable <" + key + "> to <" + value + ">. Sanity Check: " + System.getenv(key));
}

From source file:com.google.gdt.eclipse.designer.ie.util.ReflectionUtils.java

/**
 * @return the {@link Object} value of field with given name.
 *///from w w w  .  j  a  v a2  s .  com
public static Object getFieldObject(final Object object, final String name) throws Exception {
    Class<?> refClass = getRefClass(object);
    Object refObject = getRefObject(object);
    Field field = getFieldByName(refClass, name);
    if (field == null) {
        throw new IllegalArgumentException("Unable to find '" + name + "' in " + refClass);
    }
    return field.get(refObject);
}

From source file:de.Keyle.MyPet.util.BukkitUtil.java

@SuppressWarnings("unchecked")
public static boolean unregisterMyPetEntities() {
    DebugLogger.info("Unregister MyPet entities");
    try {/* ww  w  .  jav  a  2 s  . c o  m*/
        Field EntityTypes_d = EntityTypes.class.getDeclaredField("d");
        Field EntityTypes_f = EntityTypes.class.getDeclaredField("f");
        EntityTypes_d.setAccessible(true);
        EntityTypes_f.setAccessible(true);

        Map<Class, String> d = (Map) EntityTypes_d.get(EntityTypes_d);
        Map<Class, Integer> f = (Map) EntityTypes_f.get(EntityTypes_f);

        Iterator dIterator = d.keySet().iterator();
        while (dIterator.hasNext()) {
            Class clazz = (Class) dIterator.next();
            if (clazz.getCanonicalName().startsWith("de.Keyle.MyPet")) {
                dIterator.remove();
            }
        }

        Iterator fIterator = f.keySet().iterator();
        while (fIterator.hasNext()) {
            Class clazz = (Class) fIterator.next();
            if (clazz.getCanonicalName().startsWith("de.Keyle.MyPet")) {
                fIterator.remove();
            }
        }

        return true;
    } catch (Exception e) {
        DebugLogger.severe("error while unregistering MyPet entities");
        DebugLogger.severe(e.getMessage());
        return false;
    }
}

From source file:com.simple.core.util.Reflections.java

/**
 * ??, ??private/protected, ?etter?.//from ww w . j a  v  a 2s . c  om
 */
public static Object getFieldValue(final Object obj, final String fieldName) {
    Field field = getAccessibleField(obj, fieldName);

    if (field == null) {
        throw new IllegalArgumentException("Could not find field [" + fieldName + "] on target [" + obj + "]");
    }

    Object result = null;
    try {
        result = field.get(obj);
    } catch (IllegalAccessException e) {
        logger.error("??{}", e.getMessage());
    }
    return result;
}

From source file:com.haulmont.cuba.core.entity.BaseEntityInternalAccess.java

public static Object getValue(Entity entity, String attribute) {
    Preconditions.checkNotNullArgument(entity, "entity is null");
    Field field = FieldUtils.getField(entity.getClass(), attribute, true);
    if (field == null)
        throw new RuntimeException(
                String.format("Cannot find field '%s' in class %s", attribute, entity.getClass().getName()));
    try {//from   w  ww.  j  a  v a  2  s  . co  m
        return field.get(entity);
    } catch (IllegalAccessException e) {
        throw new RuntimeException(
                String.format("Unable to set value to %s.%s", entity.getClass().getSimpleName(), attribute), e);
    }
}

From source file:de.Keyle.MyPet.util.BukkitUtil.java

@SuppressWarnings("unchecked")
public static boolean registerMyPetEntity(Class<? extends EntityMyPet> myPetEntityClass, String entityTypeName,
        int entityTypeId) {
    try {//w  w w  .jav a  2  s. c o m
        Field EntityTypes_d = EntityTypes.class.getDeclaredField("d");
        Field EntityTypes_f = EntityTypes.class.getDeclaredField("f");
        EntityTypes_d.setAccessible(true);
        EntityTypes_f.setAccessible(true);

        Map<Class, String> d = (Map) EntityTypes_d.get(EntityTypes_d);
        Map<Class, Integer> f = (Map) EntityTypes_f.get(EntityTypes_f);

        Iterator cIterator = d.keySet().iterator();
        while (cIterator.hasNext()) {
            Class clazz = (Class) cIterator.next();
            if (clazz.getCanonicalName().equals(myPetEntityClass.getCanonicalName())) {
                cIterator.remove();
            }
        }

        Iterator eIterator = f.keySet().iterator();
        while (eIterator.hasNext()) {
            Class clazz = (Class) eIterator.next();
            if (clazz.getCanonicalName().equals(myPetEntityClass.getCanonicalName())) {
                eIterator.remove();
            }
        }

        d.put(myPetEntityClass, entityTypeName);
        f.put(myPetEntityClass, entityTypeId);

        return true;
    } catch (Exception e) {
        DebugLogger.severe("error while registering " + myPetEntityClass.getCanonicalName());
        DebugLogger.severe(e.getMessage());
        return false;
    }
}

From source file:cn.com.qiqi.order.utils.Reflections.java

/**
 * ?, private/protected, ??getter.// w w  w . java 2  s  .co  m
 */
public static Object getFieldValue(final Object obj, final String fieldName) {
    Field field = getAccessibleField(obj, fieldName);

    if (field == null) {
        throw new IllegalArgumentException("Could not find field [" + fieldName + "] on target [" + obj + "]");
    }

    Object result = null;
    try {
        result = field.get(obj);
    } catch (IllegalAccessException e) {
        logger.error("??{}", e.getMessage());
    }
    return result;
}

From source file:com.scvngr.levelup.core.test.JsonTestUtil.java

/**
 * <p>/*from  ww w .j  a  va  2  s.c om*/
 * Checks that modifying individual fields in a model will result in its equals/hashCode methods
 * failing. Uses reflection on {@link JsonValueType} annotations on fields of a passed class to
 * figure out how to modify the JSON representation of the model in different ways, then parses
 * the JSON with a {@link AbstractJsonModelFactory} subclass before checking equals/hashcode on
 * both the original and a modified object.
 * </p>
 * <p>
 * This effectively checks that equals/hashcode works across any value changes from fields we
 * read from JSON, but also checks some other potential issues. We're implicitly checking that
 * the JSON typing declared in annotations for the fields matches what we actually use when
 * parsing our JSON (since if it doesn't, we'll get JSON errors when reading the data during the
 * clone/modify). We're also checking for fields that may have been added to the JSON keys and
 * the model without updating equals/hashcode to reflect them (as long as they're declared in
 * the JSONKeys class used here).
 * </p>
 * <p>
 * Note that this is only intended for test use and will turn all checked exceptions it might
 * throw into unchecked ones.
 * </p>
 *
 * @param jsonKeysClass Class of the underlying keys class to test all fields (except
 *        blacklistFields) from. Must have visible fields to read from.
 * @param jsonFactory Factory object to construct model instances from out of the base and
 *        generated-variant JSON objects before checking equals/hashcode.
 * @param baseJsonObject Fully-populated JSON object for the model to use for comparison with
 *        modified copies.
 * @param blacklistFields Fields to exclude from variant testing (either because we need to test
 *        them manually or because they don't reflect fields that are used for parsing into the
 *        model). Note that this is the jsonKeysClass's field name as a string, not the JSON key
 *        value (eg "ID", not "id").
 */
public static void checkEqualsAndHashCodeOnJsonVariants(@NonNull final Class<?> jsonKeysClass,
        @NonNull final AbstractJsonModelFactory<?> jsonFactory, @NonNull final JSONObject baseJsonObject,
        @NonNull final String[] blacklistFields) {
    Object originalModel;
    Object differentModel;
    Object differentModelReparse;

    try {
        originalModel = jsonFactory.from(baseJsonObject);
    } catch (final JSONException e1) {
        throw new RuntimeException(e1);
    }

    MoreAsserts.checkEqualsAndHashCodeMethods(originalModel, null, false);

    final Field[] jsonKeyFields = jsonKeysClass.getFields();
    final List<String> blacklisted = Arrays.asList(blacklistFields);
    final String key = null;

    MoreAsserts.assertNotEmpty("JSON keys class visible fields", Arrays.asList(jsonKeyFields));

    for (final Field field : jsonKeyFields) {
        if (!blacklisted.contains(field.getName())) {
            JSONObject copiedDifferingObject;
            String fieldString;
            // Don't check exceptions, just let tests fail.
            try {
                fieldString = NullUtils.nonNullContract((String) field.get(key));
                copiedDifferingObject = cloneObjectDifferingOnParam(baseJsonObject, fieldString,
                        reflectJsonType(field));
                differentModel = jsonFactory.from(copiedDifferingObject);
                differentModelReparse = jsonFactory.from(copiedDifferingObject);
            } catch (final IllegalArgumentException e) {
                throw new RuntimeException(e);
            } catch (final IllegalAccessException e) {
                throw new RuntimeException(e);
            } catch (final JSONException e) {
                throw new RuntimeException(e);
            }

            MoreAsserts.checkEqualsAndHashCodeMethods(
                    String.format(Locale.US, "Modified %s and checked equals and hash", fieldString),
                    originalModel, differentModel, false);
            MoreAsserts.checkEqualsAndHashCodeMethods(
                    String.format(Locale.US, "Modified %s and checked equals and hash", fieldString),
                    differentModel, differentModel, true);
            MoreAsserts.checkEqualsAndHashCodeMethods(
                    String.format(Locale.US, "Modified %s and checked equals and hash", fieldString),
                    differentModel, differentModelReparse, true);
        }
    }
}

From source file:activiti.common.persistence.util.ReflectHelper.java

/**
 * ?objfieldName/*  w ww  .ja  v  a  2s.com*/
 * 
 * @param obj
 * @param fieldName
 * @return
 */
public static Object getValueByFieldName(Object obj, String fieldName) {
    Object value = null;
    try {
        Field field = getFieldByFieldName(obj, fieldName);
        if (field != null) {
            if (field.isAccessible()) {
                value = field.get(obj);
            } else {
                field.setAccessible(true);
                value = field.get(obj);
                field.setAccessible(false);
            }
        }
    } catch (Exception e) {
    }
    return value;
}

From source file:com.wsun.seap.common.utils.ReflectionsUtil.java

/**
 * ?, private/protected, ??getter./*w  w  w.j  a va2 s  .  c  om*/
 */
public static Object getFieldValue(final Object obj, final String fieldName) {
    Field field = getAccessibleField(obj, fieldName);
    if (field == null) {
        throw new IllegalArgumentException("Could not find field [" + fieldName + "] on target [" + obj + "]");
    }
    Object result = null;
    try {
        result = field.get(obj);
    } catch (IllegalAccessException e) {
        logger.error("??{}", e.getMessage());
    }
    return result;
}