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

/**
 * Helper to get the Activity result code.    This must only be called on the main thread.
 *
 * @param activity Activity whose result code is to be obtained.
 * @return Result code of the Activity.//from  www  .j ava 2 s  . c o  m
 */
public static int getActivityResultCode(@NonNull final Activity activity) {
    if (activity == null) {
        throw new IllegalArgumentException("activity cannot be null"); //$NON-NLS-1$
    }

    if (Looper.getMainLooper() != Looper.myLooper()) {
        throw new AssertionError("Must only be called on the main thread");
    }

    /*
     * This is a hack to obtain the Activity result code. There is no official way to check this using the Android
     * testing frameworks, so accessing the internals of the Activity object is the only way. This could
     * break on newer versions of Android.
     */

    try {
        final Field resultCodeField = Activity.class.getDeclaredField("mResultCode"); //$NON-NLS-1$
        resultCodeField.setAccessible(true);
        return ((Integer) resultCodeField.get(activity)).intValue();
    } catch (final Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:Main.java

public static void finishAllActivies(Activity activity) {
    try {// w w w  . j  a  va 2 s  .c om
        Class<?> clazz_Activity = Class.forName("android.app.Activity");
        Field field_mMainThread = clazz_Activity.getDeclaredField("mMainThread");
        field_mMainThread.setAccessible(true);
        Object mMainThread = field_mMainThread.get(activity);

        Class<?> clazz_ActivityThread = Class.forName("android.app.ActivityThread");
        Field field_mActivities = clazz_ActivityThread.getDeclaredField("mActivities");
        field_mActivities.setAccessible(true);
        Object mActivities = field_mActivities.get(mMainThread);

        HashMap<?, ?> map = (HashMap<?, ?>) mActivities;
        Collection<?> collections = map.values();
        if (null != collections && !collections.isEmpty()) {
            Class<?> clazz_ActivityClientRecord = Class
                    .forName("android.app.ActivityThread$ActivityClientRecord");
            Field field_activitiy = clazz_ActivityClientRecord.getDeclaredField("activity");
            field_activitiy.setAccessible(true);

            Activity acti;
            for (Object obj : collections) {
                acti = (Activity) field_activitiy.get(obj);
                Log.d(TAG, "activity.name=" + acti.getClass().getName());
                if (null != acti && !acti.isFinishing()) {
                    Log.d(TAG, "activity.name=" + acti.getClass().getName() + " not finish.");
                    acti.finish();
                }
            }
        }
    } catch (NoSuchFieldException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    } catch (IllegalArgumentException e) {
        e.printStackTrace();
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }
}

From source file:com.antsdb.saltedfish.util.CursorUtil.java

public static Record toRecord(Object obj) throws IllegalArgumentException, IllegalAccessException {
    HashMapRecord rec = new HashMapRecord();
    Class<?> klass = obj.getClass();
    for (Field i : klass.getFields()) {
        Object value = i.get(obj);
        rec.set(rec.size(), value);/*from   w  w  w.  j a v  a2s .  c  o m*/
    }
    return rec;
}

From source file:fi.jumi.test.JumiBootstrapTest.java

private static Object getDaemonOutput(JumiBootstrap bootstrap) throws Exception {
    Object out = getFieldValue(bootstrap, "daemonOutput");

    // JumiBootstrap wraps System.err into a CloseShieldOutputStream, so this code will unwrap it
    FilterOutputStream wrapper = (FilterOutputStream) out;
    Field f = FilterOutputStream.class.getDeclaredField("out");
    f.setAccessible(true);/*  w  w w.ja v a 2s.c om*/
    return f.get(wrapper);
}

From source file:edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.EditConfigurationConstants.java

public static Map<String, String> exportConstants() {
    Map<String, String> constants = new HashMap<String, String>();
    java.lang.reflect.Field[] fields = EditConfigurationConstants.class.getDeclaredFields();
    for (java.lang.reflect.Field f : fields) {
        if (Modifier.isStatic(f.getModifiers()) && Modifier.isPublic(f.getModifiers())) {
            try {
                constants.put(f.getName(), f.get(null).toString());
            } catch (Exception ex) {
                log.error("An exception occurred in trying to retrieve this field ", ex);
            }/*from w w w  . j av a2  s.c om*/
        }
    }
    return constants;
}

From source file:com.googlecode.easymockrule.EasyMockUtils.java

/**
 * Get the mock control "type" field value or empty string on error.
 * //from   ww w  .j  a v  a2 s  .c om
 * @param mock
 * @return
 */
public static String getMockType(Object mock) {

    try {
        MocksControl mockControl = getMockControl(mock);

        Field mockTypeField = mockControl.getClass().getDeclaredField("type");
        mockTypeField.setAccessible(true);

        MockType mockType = (MockType) mockTypeField.get(mockControl);

        return mockType.toString();

    } catch (Exception e) {
        return StringUtils.EMPTY;
    }
}

From source file:Main.java

/**
 * @param context if null, use the default format
 *                (Mozilla/5.0 (Linux; U; Android %s) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 %sSafari/534.30).
 * @return/*from w  ww.  j  a va  2 s.c  o m*/
 */
public static String getUserAgent(Context context) {
    String webUserAgent = null;
    if (context != null) {
        try {
            Class sysResCls = Class.forName("com.android.internal.R$string");
            Field webUserAgentField = sysResCls.getDeclaredField("web_user_agent");
            Integer resId = (Integer) webUserAgentField.get(null);
            webUserAgent = context.getString(resId);
        } catch (Throwable ignored) {
        }
    }
    if (TextUtils.isEmpty(webUserAgent)) {
        webUserAgent = "Mozilla/5.0 (Linux; U; Android %s) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 %sSafari/533.1";
    }

    Locale locale = Locale.getDefault();
    StringBuffer buffer = new StringBuffer();
    // Add version
    final String version = Build.VERSION.RELEASE;
    if (version.length() > 0) {
        buffer.append(version);
    } else {
        // default to "1.0"
        buffer.append("1.0");
    }
    buffer.append("; ");
    final String language = locale.getLanguage();
    if (language != null) {
        buffer.append(language.toLowerCase());
        final String country = locale.getCountry();
        if (country != null) {
            buffer.append("-");
            buffer.append(country.toLowerCase());
        }
    } else {
        // default to "en"
        buffer.append("en");
    }
    // add the model for the release build
    if ("REL".equals(Build.VERSION.CODENAME)) {
        final String model = Build.MODEL;
        if (model.length() > 0) {
            buffer.append("; ");
            buffer.append(model);
        }
    }
    final String id = Build.ID;
    if (id.length() > 0) {
        buffer.append(" Build/");
        buffer.append(id);
    }
    return String.format(webUserAgent, buffer, "Mobile ");
}

From source file:Main.java

/**
 * Helper to get the Activity result Intent.  This must only be called on the main thread.
 *
 * @param activity Activity whose result Intent is to be obtained.
 * @return Result Intent of the Activity.
 *//*from   w ww.j  a v  a2s . co  m*/
@Nullable
public static Intent getActivityResultData(@NonNull final Activity activity) {
    if (activity == null) {
        throw new IllegalArgumentException("activity cannot be null"); //$NON-NLS-1$
    }

    if (Looper.getMainLooper() != Looper.myLooper()) {
        throw new AssertionError("Must only be called on the main thread");
    }

    /*
     * This is a hack to obtain the Activity result data. There is no official way to check this using the Android
     * testing frameworks, so accessing the internals of the Activity object is the only way. This could
     * break on newer versions of Android.
     */

    try {
        final Field resultIntentField = Activity.class.getDeclaredField("mResultData"); //$NON-NLS-1$
        resultIntentField.setAccessible(true);
        return ((Intent) resultIntentField.get(activity));
    } catch (final Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:Main.java

/**
 * Enable/Disable mobile data.//from  w w  w .  j ava  2  s . co m
 * @param context
 * @param enabled
 */
public static void setMobileDataEnabled(Context context, boolean enabled) {
    try {
        final ConnectivityManager conman = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        final Class conmanClass = Class.forName(conman.getClass().getName());
        final Field connectivityManagerField = conmanClass.getDeclaredField("mService");
        connectivityManagerField.setAccessible(true);
        final Object connectivityManager = connectivityManagerField.get(conman);
        final Class connectivityManagerClass = Class.forName(connectivityManager.getClass().getName());
        final Method setMobileDataEnabledMethod = connectivityManagerClass
                .getDeclaredMethod("setMobileDataEnabled", Boolean.TYPE);
        setMobileDataEnabledMethod.setAccessible(true);
        // Method call for enabling mobile data..
        setMobileDataEnabledMethod.invoke(connectivityManager, enabled);
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    } catch (NoSuchFieldException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    } catch (NoSuchMethodException e) {
        e.printStackTrace();
    } catch (InvocationTargetException e) {
        e.printStackTrace();
    }
}

From source file:io.wcm.caravan.commons.httpasyncclient.impl.HttpClientTestUtils.java

private static Object getField(Object object, Class clazz, String fieldName) {
    Field field;
    try {//from  w ww  .jav  a 2 s.co m
        field = clazz.getDeclaredField(fieldName);
        field.setAccessible(true);
        return field.get(object);
    } catch (NoSuchFieldException ex) {
        Class superClazz = clazz.getSuperclass();
        if (superClazz != null) {
            return getField(object, superClazz, fieldName);
        } else {
            throw new RuntimeException("Unable to get field value for '" + fieldName + "'.", ex);
        }
    } catch (SecurityException | IllegalArgumentException | IllegalAccessException ex) {
        throw new RuntimeException("Unable to get field value for '" + fieldName + "'.", ex);
    }
}