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:edu.wright.daselab.linkgen.ConfigurationParams.java

public final static boolean checkStatusOnLoad() throws Exception {
    // using reflection to check all properties/params fields.
    // you can use annotation for better retrieval
    // http://stackoverflow.com/questions/2020202/pitfalls-in-getting-member-variable-values-in-java-with-reflection
    // by this time, none of the values are empty.
    String name = "";
    String value = "";
    logger.info("Displaying all param values:");
    boolean isFine = true;
    Field[] fields = ConfigurationParams.class.getDeclaredFields();
    for (Field field : fields) {
        // check only final static fields
        if (!Modifier.isFinal((field.getModifiers())) || (!Modifier.isStatic(field.getModifiers()))) {
            continue;
        }//from   w w  w . j  av a  2  s. c o m
        name = field.getName();
        try {
            value = (String) field.get(null).toString();
        } catch (Exception e) {
            Monitor.error(Error.INVALID_CONFIG_PARAMS.toString());
            throw new IllegalArgumentException(Error.INVALID_CONFIG_PARAMS.toString());
        }
        if ((value == null) || value.toString().trim().equals("")) {
            isFine = false;
        }
        String status = isFine ? "OK" : "Failed";
        logger.info(status + " \t" + name + "=" + value);
        if (!isFine)
            throw new IllegalArgumentException(Error.INVALID_CONFIG_PARAMS.toString());
    }
    return isFine;
}

From source file:com.sonatype.security.ldap.api.DeepEqualsBuilder.java

private static void reflectionAppend(Object lhs, Object rhs, Class clazz, EqualsBuilder builder,
        boolean useTransients, String[] excludeFields) {
    while (clazz.getSuperclass() != null) {

        Field[] fields = clazz.getDeclaredFields();
        List excludedFieldList = excludeFields != null ? Arrays.asList(excludeFields) : Collections.EMPTY_LIST;
        AccessibleObject.setAccessible(fields, true);
        for (int i = 0; i < fields.length && builder.isEquals(); i++) {
            Field f = fields[i];
            if (!excludedFieldList.contains(f.getName()) && (f.getName().indexOf('$') == -1)
                    && (useTransients || !Modifier.isTransient(f.getModifiers()))
                    && (!Modifier.isStatic(f.getModifiers()))) {
                try {
                    Object lhsChild = f.get(lhs);
                    Object rhsChild = f.get(rhs);
                    Class testClass = getTestClass(lhsChild, rhsChild);
                    boolean hasEqualsMethod = classHasEqualsMethod(testClass);

                    if (testClass != null && !hasEqualsMethod) {
                        reflectionAppend(lhsChild, rhsChild, testClass, builder, useTransients, excludeFields);
                    } else {
                        builder.append(lhsChild, rhsChild);
                    }/*from   w ww.j a v  a 2s. c o m*/
                } catch (IllegalAccessException e) {
                    // this can't happen. Would get a Security exception instead
                    // throw a runtime exception in case the impossible happens.
                    throw new InternalError("Unexpected IllegalAccessException");
                }
            }
        }

        // now for the parent
        clazz = clazz.getSuperclass();
        reflectionAppend(lhs, rhs, clazz, builder, useTransients, excludeFields);
    }
}

From source file:Main.java

public static String[] getClassStaticFieldNames(Class c, Type fieldType, String nameContains) {
    Field[] fields = c.getDeclaredFields();
    List<String> list = new ArrayList<>();
    for (Field field : fields) {
        try {/*  ww w. j  av a2s .  c  o m*/
            boolean isString = field.getType().equals(fieldType);
            boolean containsExtra = field.getName().contains(nameContains);
            boolean isStatic = Modifier.isStatic(field.getModifiers());
            if (field.getType().equals(String.class) && field.getName().contains("EXTRA_")
                    && Modifier.isStatic(field.getModifiers()))
                list.add(String.valueOf(field.get(null)));
        } catch (IllegalAccessException iae) {
            Log.d(TAG,
                    "!!!!!!!!!!!! class Static field, illegal access exception message: " + iae.getMessage());
        }
    }
    return list.toArray(new String[list.size()]);
}

From source file:com.iflytek.edu.cloud.frame.utils.ReflectionUtils.java

/**
 * ?,private/protected,??getter./*from  ww w  .  j av a 2s.c o  m*/
 */
public static Object getFieldValue(final Object object, final String fieldName) {
    Field field = getDeclaredField(object, fieldName);

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

    makeAccessible(field);

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

From source file:me.neatmonster.spacebukkit.PanelListener.java

public static String dump(Object object) {
    Field[] fields = object.getClass().getDeclaredFields();
    StringBuilder sb = new StringBuilder();
    sb.append(object.getClass().getSimpleName()).append('{');

    boolean firstRound = true;

    for (Field field : fields) {
        if (!firstRound) {
            sb.append(", ");
        }/*from   w w w  .ja  v a 2  s .c  om*/
        firstRound = false;
        field.setAccessible(true);
        try {
            final Object fieldObj = field.get(object);
            final String value;
            if (null == fieldObj) {
                value = "null";
            } else {
                value = fieldObj.toString();
            }
            sb.append(field.getName()).append('=').append('\'').append(value).append('\'');
        } catch (IllegalAccessException ignore) {
            //this should never happen
        }

    }

    sb.append('}');
    return sb.toString();
}

From source file:brooklyn.entity.software.SshEffectorTasksTest.java

public static Integer getMyPid() {
    try {//  w ww  . ja v  a  2  s.c om
        java.lang.management.RuntimeMXBean runtime = java.lang.management.ManagementFactory.getRuntimeMXBean();
        java.lang.reflect.Field jvm = runtime.getClass().getDeclaredField("jvm");
        jvm.setAccessible(true);
        //            sun.management.VMManagement mgmt = (sun.management.VMManagement) jvm.get(runtime);
        Object mgmt = jvm.get(runtime);
        java.lang.reflect.Method pid_method = mgmt.getClass().getDeclaredMethod("getProcessId");
        pid_method.setAccessible(true);

        return (Integer) pid_method.invoke(mgmt);
    } catch (Exception e) {
        throw new PropagatedRuntimeException(
                "Test depends on (fragile) getMyPid method which does not work here", e);
    }
}

From source file:com.taobao.android.builder.tools.guide.AtlasConfigHelper.java

public static void setProperty(Object object, String fieldName, String value)
        throws IllegalAccessException, InstantiationException, InvocationTargetException, NoSuchFieldException {

    String[] fieldNames = fieldName.split("\\.");

    Object last = object;/*from  w  w w.  ja va  2 s.c  o  m*/
    for (int i = 0; i < fieldNames.length - 1; i++) {

        String field = fieldNames[i];

        if (last instanceof NamedDomainObjectContainer) {
            last = ((NamedDomainObjectContainer) last).maybeCreate(field);
        } else {
            Field declaredField = last.getClass().getField(field);
            declaredField.setAccessible(true);

            if (null == declaredField.get(last)) {
                Object newInstance = declaredField.getType().getConstructors().getClass().newInstance();
                declaredField.set(last, newInstance);
            }

            last = declaredField.get(last);
        }
    }

    BeanUtils.setProperty(last, fieldNames[fieldNames.length - 1], value);
}

From source file:edu.mit.csail.sdg.alloy4.Terminal.java

static boolean getBoolean(Field f, Object obj) {
    f.setAccessible(true);//from ww  w.java  2s .  co m

    try {
        return (Boolean) f.get(obj);

    } catch (IllegalArgumentException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return false;
}

From source file:com.fengduo.bee.commons.util.ObjectUtils.java

/**
 * string?trim?/*from   ww  w .  jav  a  2 s .c  o m*/
 * 
 * @param object
 * @throws Exception
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
private static void trimStringField(Object object, Class<?> clazz) throws Exception {
    if (object instanceof Map<?, ?>) {
        Map<Object, Object> target = new HashMap<Object, Object>();
        for (Entry<?, ?> entry : ((Map<?, ?>) object).entrySet()) {
            Object key = entry.getKey();
            Object value = entry.getValue();

            if (key instanceof String) {
                key = StringUtils.trim((String) key);
            } else {
                trim(key);
            }

            if (value instanceof String) {
                value = StringUtils.trim((String) value);
                value = StringUtils.replace((String) value, "\"", StringUtils.EMPTY);
            } else {
                trim(value);
            }
            target.put(key, value);
        }
        ((Map<?, ?>) object).clear();
        ((Map) object).putAll((Map) target);
        return;
    }
    Field[] fields = clazz.getDeclaredFields();
    for (Field field : fields) {
        if (field.getType() == String.class) {
            boolean isFoolback = false;
            if (field.isAccessible() == false) {
                isFoolback = true;
                field.setAccessible(true);
            }
            String value = (String) field.get(object);
            if (StringUtils.isNotEmpty(value)) {
                value = value.trim();
                field.set(object, value);
            }
            if (isFoolback) {
                field.setAccessible(false);
            }
        }
    }
}

From source file:com.joyent.manta.client.MantaObjectOutputStream.java

/**
 * Finds the most inner stream if the embedded stream is stored on the passed
 * stream as a field named <code>out</code>. This hold true for all classes
 * that extend {@link java.io.FilterOutputStream}.
 *
 * @param stream stream to search for inner stream
 * @return reference to inner stream class
 *//*  w w  w  .  jav  a2 s.c o  m*/
protected static OutputStream findMostInnerOutputStream(final OutputStream stream) {
    Field f = FieldUtils.getField(stream.getClass(), "out", true);

    if (f == null) {
        return stream;
    } else {
        try {
            Object result = f.get(stream);

            if (result instanceof OutputStream) {
                return findMostInnerOutputStream((OutputStream) result);
            } else {
                return stream;
            }
        } catch (IllegalAccessException e) {
            // If we can't access the field, then we just return back the original stream
            return stream;
        }
    }
}