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:Main.java

/**
 * Get a Hashtable of all class member fields (including private) of the
 * given object/*from  w w  w.  j a va  2  s .  c  o  m*/
 * 
 * @param objectInstance Object to get data from
 * @return Hashtable of all values
 * 
 * @throws IllegalArgumentException
 * @throws IllegalAccessException
 */
public static Map<String, Object> getAllFields(Object objectInstance)
        throws IllegalArgumentException, IllegalAccessException // NOSONAR
{
    HashMap<String, Object> map = new HashMap<String, Object>();

    Class<? extends Object> clazz = objectInstance.getClass();

    Field fields[] = clazz.getDeclaredFields();
    for (int i = 0; i < fields.length; i++) {
        Field f = fields[i];
        f.setAccessible(true);

        String fieldName = f.getName();
        Object fieldValue = f.get(objectInstance);

        map.put(fieldName, fieldValue);
    }

    return map;
}

From source file:io.apiman.plugins.keycloak_oauth_policy.ClaimLookup.java

private static String callClaimChain(Object rootObject, List<Field> list) {
    try {//from ww  w  .j a  va 2  s. c  o  m
        Object candidate = rootObject;
        for (Field f : list) {
            if ((candidate = f.get(candidate)) == null)
                break;
        }
        return (candidate == null) ? null : candidate.toString();
    } catch (IllegalArgumentException | IllegalAccessException e) {
        // TODO Use logger. These exceptions shouldn't occur, but if it somehow does happen we need to know.
        System.err.println("Unexpected error looking up token field: " + e); //$NON-NLS-1$
        e.printStackTrace();
    }
    return null;
}

From source file:Main.java

private static int getImageViewFieldValue(Object object, String fieldName) {
    int value = 0;
    if (object instanceof ImageView) {
        try {// w w w . j a v  a2s.  com
            Field field = ImageView.class.getDeclaredField(fieldName);
            field.setAccessible(true);
            int fieldValue = (Integer) field.get(object);
            if (fieldValue > 0 && fieldValue < Integer.MAX_VALUE) {
                value = fieldValue;
            }
        } catch (Throwable e) {
        }
    }
    return value;
}

From source file:Main.java

/**
 * Decode a variable. Variables are in the form $varname. If the incoming
 * expression is not a variable or is not recognised it is simply returned
 * verbatim.//w ww  .  j  a v  a  2  s .  com
 * @param in The incoming attribute
 * @return String
 * @throws Exception
 */
private static String decode(String in) throws Exception {
    if (in != null && in.length() > 1 && in.charAt(0) == '$') {
        String key = in.substring(1);
        if (key.charAt(0) == '#') {
            // It's a class name and reflection job in the form $$full.class.name.member
            int lastIdx = key.lastIndexOf('.');
            String member = key.substring(lastIdx + 1);
            String className = key.substring(1, lastIdx);
            Class<?> clazz = Class.forName(className);
            Field field = clazz.getDeclaredField(member);
            field.setAccessible(true);
            return String.valueOf(field.get(null));
        } else {
            String val = vars.get(key);
            if (val == null) {
                throw new Exception("Unknown variable " + in);
            } else {
                return val;
            }
        }
    } else {
        return in;
    }
}

From source file:Main.java

public static Object toSerializableObject(Object obj) {
    // Case for objects have no specified method to JSON string.
    if (obj.getClass().isArray()) {
        JSONArray result = new JSONArray();
        Object[] arr = (Object[]) obj;
        for (int i = 0; i < arr.length; ++i) {
            try {
                result.put(i, toSerializableObject(arr[i]));
            } catch (Exception e) {
                e.printStackTrace();/*from   w w w.  j a  v  a 2 s. c  o  m*/
            }
        }
        return result;
    }
    // The original serializable object.
    if (isSerializable(obj))
        return obj;

    // Customized serializable object.
    //
    // If the object is not directly serializable, we check if it is customised
    // serializable. That means the developer implemented the public serialization
    // method "toJSONString".
    try {
        Method m = obj.getClass().getMethod("toJSONString", new Class<?>[0]);
        String jsonStr = (String) (m.invoke(obj, new Object[0]));
        if (jsonStr.trim().charAt(0) == '[') {
            return new JSONArray(jsonStr);
        } else {
            return new JSONObject(jsonStr);
        }
    } catch (Exception e) {
        Log.w(TAG, "No serialization method: \"toJSONString\", or errors happened.");
    }

    /*
     * For ordinary objects, we will just serialize the accessible fields.
     */
    try {
        Class<?> c = obj.getClass();
        JSONObject json = new JSONObject();
        Field[] fields = c.getFields();
        for (Field f : fields) {
            json.put(f.getName(), f.get(obj));
        }
        return json;
    } catch (Exception e) {
        Log.e(TAG, "Field to serialize object to JSON.");
        e.printStackTrace();
        return null;
    }
}

From source file:Main.java

public static Object invokeField(Class<?> cls, Object object, String fieldName) throws Exception {
    Field field = cls.getDeclaredField(fieldName);

    boolean accessible = field.isAccessible();
    try {//from w  w  w.j a  v  a2  s .  co  m
        field.setAccessible(true);
        return field.get(object);
    } finally {
        field.setAccessible(accessible);
    }
}

From source file:Main.java

/**
 * get GridView vertical spacing/*from w  w w  .  j  a v  a 2  s.  c o m*/
 * 
 * @param view
 * @return
 */
public static int getGridViewVerticalSpacing(GridView view) {
    // get mVerticalSpacing by android.widget.GridView
    Class<?> demo = null;
    int verticalSpacing = 0;
    try {
        demo = Class.forName(CLASS_NAME_GRID_VIEW);
        Field field = demo.getDeclaredField(FIELD_NAME_VERTICAL_SPACING);
        field.setAccessible(true);
        verticalSpacing = (Integer) field.get(view);
        return verticalSpacing;
    } catch (Exception e) {
        /**
         * accept all exception, include ClassNotFoundException, NoSuchFieldException, InstantiationException,
         * IllegalArgumentException, IllegalAccessException, NullPointException
         */
        e.printStackTrace();
    }
    return verticalSpacing;
}

From source file:io.fns.calculator.filter.CORSFilter.java

private static Object getInstanceField(Object instance, String fieldName) throws Throwable {
    Field field = instance.getClass().getSuperclass().getDeclaredField(fieldName);
    field.setAccessible(true);/*from  w ww.j  a v a2  s.  c  o  m*/
    return field.get(instance);
}

From source file:Main.java

/**
 * Check application's R.id class and retrieve the value of the static
 * member with the given name./*  w  w w . ja  v  a  2s. co  m*/
 */
public static int getIdentifierFromR(Context context, String type, String name) {
    Class<?> rClass = null;
    try {
        rClass = Class.forName(context.getPackageName() + ".R$" + type);
    } catch (ClassNotFoundException e) {
        // No R.id class? This should never happen.
        throw new RuntimeException(e);
    }

    try {
        Field rField = rClass.getField(name);
        Object intValue;
        try {
            intValue = rField.get(null);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }
        if (!(intValue instanceof Integer)) {
            throw new RuntimeException("Not an int: " + rClass.getCanonicalName() + "." + rField.getName());
        }
        return ((Integer) intValue).intValue();
    } catch (NoSuchFieldException e) {
        throw new RuntimeException("There is no such id in the R class: " + context.getPackageName() + ".R."
                + type + "." + name + ")");
    } catch (SecurityException e) {
        throw new RuntimeException(e);
    }
}

From source file:Main.java

public static Object set(Field f, Object obj, Object value)
        throws IllegalArgumentException, IllegalAccessException {
    f.setAccessible(true);/*from ww w.  j  av a 2  s  . c  o  m*/
    f.set(obj, value);
    return f.get(obj);
}