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.netflix.spinnaker.clouddriver.aws.security.AmazonClientInvocationHandler.java

private static Collection<String> getRequestIds(AmazonWebServiceRequest request, String idFieldName) {
    if (request == null) {
        return Collections.emptySet();
    }//from  w ww .j  a v  a2 s . co  m
    try {
        Field field = request.getClass().getDeclaredField(idFieldName);
        field.setAccessible(true);
        Collection<String> collection = (Collection<String>) field.get(request);
        return collection == null ? Collections.emptySet() : collection;
    } catch (NoSuchFieldException | IllegalAccessException e) {
        throw new RuntimeException(e);
    }
}

From source file:cn.whereyougo.framework.utils.PackageManagerUtil.java

/**
 * ??,json//from  w w  w.jav a2  s.  com
 * 
 * @param ctx
 */
public static JSONObject collectDeviceInfo(Context ctx) {
    JSONObject result = new JSONObject();
    Field[] fields = Build.class.getDeclaredFields();
    for (Field field : fields) {
        try {
            field.setAccessible(true);
            result.put(field.getName(), field.get(null).toString());
        } catch (Exception e) {
            LogUtil.d(TAG, "an error occured when collect device info " + e.getMessage());
        }
    }

    return result;
}

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

/**
 * Given an {@link Object} and a {@link Field} of a known {@link Class} type, get the field.
 * This will return the value of the field regardless of visibility modifiers (i.e., it will
 * return the value of private fields.)/*from  w  w  w  .  ja  va2s .  c  o  m*/
 */
public static <T> T getFieldObject(Object object, Field field, Class<T> klass) {
    try {
        boolean accessible = field.isAccessible();
        field.setAccessible(true);
        Object fieldObject = field.get(object);
        field.setAccessible(accessible);
        return klass.cast(fieldObject);
    } catch (IllegalAccessException e) {
        // shouldn't happen since we set accessibility above.
        return null;
    }
}

From source file:com.xhsoft.framework.common.utils.ReflectionUtils.java

/**
 * <p>Description:?, private/protected, ??getter.</p>
 * @param obj//from  www  .ja  va2  s . co m
 * @param fieldName
 * @return Object
 */
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:de.unisb.cs.st.javalanche.mutation.util.AddOffutt96Sufficient.java

private static int getOriginalValue(String addInfo) {
    String substring = addInfo.substring("Replace ".length());
    int index = substring.indexOf(' ');
    String s = substring.substring(0, index);
    try {/*  ww w . ja v  a 2  s  .  co  m*/
        Field field = Opcodes.class.getField(s);
        int val = (Integer) field.get(null);
        return val;
    } catch (SecurityException e) {
        e.printStackTrace();
    } catch (NoSuchFieldException e) {
        e.printStackTrace();
    } catch (IllegalArgumentException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    }
    return Integer.parseInt(s);
}

From source file:org.red5.server.api.ScopeUtils.java

public static Object getScopeService(IScope scope, Class intf, Class defaultClass, boolean checkHandler) {
    if (scope == null || intf == null) {
        return null;
    }/*  ww  w  .j ava 2s  .  c  o  m*/
    // We expect an interface
    assert intf.isInterface();

    if (scope.hasAttribute(IPersistable.TRANSIENT_PREFIX + SERVICE_CACHE_PREFIX + intf.getCanonicalName())) {
        // Return cached service
        return scope
                .getAttribute(IPersistable.TRANSIENT_PREFIX + SERVICE_CACHE_PREFIX + intf.getCanonicalName());
    }

    Object handler = null;
    if (checkHandler) {
        IScope current = scope;
        while (current != null) {
            IScopeHandler scopeHandler = current.getHandler();
            if (intf.isInstance(scopeHandler)) {
                handler = scopeHandler;
                break;
            }

            if (!current.hasParent())
                break;

            current = current.getParent();
        }
    }

    if (handler == null && IScopeService.class.isAssignableFrom(intf)) {
        // We got an IScopeService, try to lookup bean
        Field key = null;
        Object serviceName = null;
        try {
            key = intf.getField("BEAN_NAME");
            serviceName = key.get(null);
            if (!(serviceName instanceof String))
                serviceName = null;
        } catch (Exception e) {
            log.debug("No string field 'BEAN_NAME' in that interface");
        }

        if (serviceName != null)
            handler = getScopeService(scope, (String) serviceName, defaultClass);
    }

    if (handler == null && defaultClass != null) {
        try {
            handler = defaultClass.newInstance();
        } catch (Exception e) {
            log.error(e);
        }
    }

    // Cache service
    scope.setAttribute(IPersistable.TRANSIENT_PREFIX + SERVICE_CACHE_PREFIX + intf.getCanonicalName(), handler);
    return handler;
}

From source file:io.github.sparta.helpers.reflex.Reflections.java

/** ?, private/protected, ??getter. */
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 + "]");
    }//from  w w  w .  j  a  v  a  2s . c om

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

From source file:com.jeysan.modules.utils.reflection.ReflectionUtils.java

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

From source file:org.dawnsci.commandserver.core.process.ProgressableProcess.java

protected static int getPid(Process p) throws Exception {

    if (Platform.isWindows()) {
        Field f = p.getClass().getDeclaredField("handle");
        f.setAccessible(true);//from   w  w  w . j  av  a 2s .c  o m
        int pid = Kernel32.INSTANCE.GetProcessId((Long) f.get(p));
        return pid;

    } else if (Platform.isLinux()) {
        Field f = p.getClass().getDeclaredField("pid");
        f.setAccessible(true);
        int pid = (Integer) f.get(p);
        return pid;

    } else {
        throw new Exception("Cannot currently process pid for " + System.getProperty("os.name"));
    }
}

From source file:edu.usu.sdl.openstorefront.core.util.EntityUtil.java

/**
 * This will set default on the fields that are marked with a default and
 * are null/* w w w . j a  va2s .  c om*/
 *
 * @param entity
 */
public static void setDefaultsOnFields(Object entity) {
    Objects.requireNonNull(entity, "Entity must not be NULL");
    List<Field> fields = getAllFields(entity.getClass());
    for (Field field : fields) {
        DefaultFieldValue defaultFieldValue = field.getAnnotation(DefaultFieldValue.class);
        if (defaultFieldValue != null) {
            field.setAccessible(true);
            try {
                if (field.get(entity) == null) {
                    String value = defaultFieldValue.value();
                    Class fieldClass = field.getType();
                    if (fieldClass.getSimpleName().equalsIgnoreCase(String.class.getSimpleName())) {
                        field.set(entity, value);
                    } else if (fieldClass.getSimpleName().equalsIgnoreCase(Long.class.getSimpleName())) {
                        field.set(entity, value);
                    } else if (fieldClass.getSimpleName().equalsIgnoreCase(Integer.class.getSimpleName())) {
                        field.set(entity, Integer.parseInt(value));
                    } else if (fieldClass.getSimpleName().equalsIgnoreCase(Boolean.class.getSimpleName())) {
                        field.set(entity, Convert.toBoolean(value));
                    } else if (fieldClass.getSimpleName().equalsIgnoreCase(Double.class.getSimpleName())) {
                        field.set(entity, Double.parseDouble(value));
                    } else if (fieldClass.getSimpleName().equalsIgnoreCase(Float.class.getSimpleName())) {
                        field.set(entity, Float.parseFloat(value));
                    } else if (fieldClass.getSimpleName().equalsIgnoreCase(BigDecimal.class.getSimpleName())) {
                        field.set(entity, Convert.toBigDecimal(value));
                    } else if (fieldClass.getSimpleName().equalsIgnoreCase(Date.class.getSimpleName())) {
                        field.set(entity, TimeUtil.fromString(value));
                    } else if (fieldClass.getSimpleName().equalsIgnoreCase(BigInteger.class.getSimpleName())) {
                        field.set(entity, new BigInteger(value));
                    }
                }
            } catch (IllegalArgumentException | IllegalAccessException ex) {
                throw new OpenStorefrontRuntimeException(
                        "Unable to get value on " + entity.getClass().getName(), "Check entity passed in.");
            }
        }
    }
}