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.lpm.fanger.commons.util.Reflections.java

/**
 * ?, private/protected, ??getter.//from  ww w.j av a  2s  .  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) {
        e.printStackTrace();
    }
    return result;
}

From source file:com.autobizlogic.abl.util.BeanUtil.java

protected static Object getValueWithField(Field field, Object bean) {

    try {/*from w  w  w  .j a  v a 2s.  c om*/
        field.setAccessible(true);
        return field.get(bean);
    } catch (Exception ex) {
        throw new RuntimeException("Unable to get property " + field.getName() + " on instance of "
                + bean.getClass().getName() + " using field " + field.getName(), ex);
    }
}

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  ww w  . j  av  a2  s . c om
            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:com.kangyonggan.api.common.util.Reflections.java

/**
 * ?, private/protected, ??getter./*from   ww w . j a  va  2  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) {
        log.error("??{}", e.getMessage());
    }
    return result;
}

From source file:$.Reflections.java

/**
     * ?, private/protected, ??getter./*from   w  w w.  ja v  a  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:edu.usu.sdl.openstorefront.core.util.EntityUtil.java

/**
 * Compares to consume fields of two object of the same type Note this won't
 * work with proxy object.//from   w  w w .  j ava2  s . c o m
 *
 * @param original
 * @param compare
 * @return compare value (0 if equals)
 */
public static int compareConsumeFields(Object original, Object compare) {
    int value = 0;
    if (original != null && compare == null) {
        value = -1;
    } else if (original == null && compare != null) {
        value = 1;
    } else if (original != null && compare != null) {
        if (original.getClass().isInstance(compare)) {
            List<Field> fields = getAllFields(original.getClass());
            for (Field field : fields) {
                ConsumeField consume = (ConsumeField) field.getAnnotation(ConsumeField.class);
                if (consume != null) {
                    try {
                        field.setAccessible(true);
                        value = compareObjects((Comparable) field.get(original),
                                (Comparable) field.get(compare));
                        if (value != 0) {
                            break;
                        }
                    } catch (IllegalArgumentException | IllegalAccessException ex) {
                        throw new OpenStorefrontRuntimeException("Can't compare object fields", ex);
                    }
                }
            }
        } else {
            throw new OpenStorefrontRuntimeException("Can't compare different object types", "Check objects");
        }
    }
    return value;
}

From source file:com.ms.commons.test.classloader.IntlTestURLClassPath.java

private static URLClassPath getLauncherUrlClassPath(URLClassLoader classLoader) {
    try {/*from w  ww  . java 2s  .  co  m*/
        Field ucpField = URLClassLoader.class.getDeclaredField("ucp");
        ucpField.setAccessible(true);
        return (URLClassPath) ucpField.get(classLoader);
    } catch (Exception e) {
        throw ExceptionUtil.wrapToRuntimeException(e);
    }
}

From source file:com.kcs.core.utilities.Utility.java

public static void nullToEmptyString(final Object obj) {
    ReflectionUtils.doWithFields(obj.getClass(), new ReflectionUtils.FieldCallback() {
        @Override// w  w  w. j a  v a  2s  . co m
        public void doWith(final Field field) throws IllegalArgumentException, IllegalAccessException {
            field.setAccessible(true);
            if (Utility.isNull(field.get(obj))) {
                Class<?> clazz = field.getType();
                if (clazz == String.class) {
                    field.set(obj, StringUtil.BLANK);
                }
            }
        }
    });
}

From source file:org.orderofthebee.addons.support.tools.repo.caches.CacheLookupUtils.java

/**
 * Retrieves the statistics data from an Alfresco Enterprise Edition {@code InvalidatingCache}
 *
 * @param invalidatingCache//  w  w  w  .ja v a 2  s.  c  o  m
 *            the invalidating cache
 * @return the statistics object
 * @throws Exception
 *             if the reflective access fails for any reason
 */
public static Object getHzInvalidatingCacheStats(final SimpleCache<?, ?> invalidatingCache) throws Exception {
    ParameterCheck.mandatory("invalidatingCache", invalidatingCache);

    final Field cacheField = invalidatingCache.getClass().getDeclaredField("cache");
    // will fail in Java 9 but no other way due to private visibility, Enterprise-only class and lack of accessor
    cacheField.setAccessible(true);
    final Object internalCache = cacheField.get(invalidatingCache);

    if (!(internalCache instanceof DefaultSimpleCache<?, ?>)) {
        throw new IllegalArgumentException("internalCache should be an instance of DefaultSimpleCache");
    }

    return getDefaultSimpleCacheStats((DefaultSimpleCache<?, ?>) internalCache);
}

From source file:org.artifactory.util.HttpUtils.java

public static String resolveResponseRemoteAddress(CloseableHttpResponse response) {
    try {//from   www . j av a2s.c  o m
        Field connHolderField = response.getClass().getDeclaredField("connHolder");
        connHolderField.setAccessible(true);
        Object connHolder = connHolderField.get(response);

        Field managedConnField = connHolder.getClass().getDeclaredField("managedConn");
        managedConnField.setAccessible(true);
        ManagedHttpClientConnection managedConn = (ManagedHttpClientConnection) managedConnField
                .get(connHolder);
        String hostAddress = managedConn.getSocket().getInetAddress().getHostAddress();
        return hostAddress == null ? StringUtils.EMPTY : hostAddress;
    } catch (Throwable throwable) {
        return StringUtils.EMPTY;
    }
}