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.bt.download.android.gui.UniversalScanner.java

private static Uri nativeScanFile(Context context, String path) {
    try {/*w w w.  j a v  a  2s.  c o  m*/
        File f = new File(path);

        Class<?> clazz = Class.forName("android.media.MediaScanner");

        Constructor<?> mediaScannerC = clazz.getDeclaredConstructor(Context.class);
        Object scanner = mediaScannerC.newInstance(context);

        Field mClientF = clazz.getDeclaredField("mClient");
        mClientF.setAccessible(true);
        Object mClient = mClientF.get(scanner);

        Method scanSingleFileM = clazz.getDeclaredMethod("scanSingleFile", String.class, String.class,
                String.class);
        Uri fileUri = (Uri) scanSingleFileM.invoke(scanner, f.getAbsolutePath(), "external", "data/raw");
        int n = context.getContentResolver().delete(fileUri, null, null);
        if (n > 0) {
            LOG.debug("Deleted from Files provider: " + fileUri);
        }

        Field mNoMediaF = mClient.getClass().getDeclaredField("mNoMedia");
        mNoMediaF.setAccessible(true);
        mNoMediaF.setBoolean(mClient, false);

        // This is only for HTC (tested only on HTC One M8)
        try {
            Field mFileCacheF = clazz.getDeclaredField("mFileCache");
            mFileCacheF.setAccessible(true);
            mFileCacheF.set(scanner, new HashMap<String, Object>());
        } catch (Throwable e) {
            // no an HTC, I need some time to refactor this hack
        }

        Method doScanFileM = mClient.getClass().getDeclaredMethod("doScanFile", String.class, String.class,
                long.class, long.class, boolean.class, boolean.class, boolean.class);
        Uri mediaUri = (Uri) doScanFileM.invoke(mClient, f.getAbsolutePath(), null, f.lastModified(),
                f.length(), false, true, false);

        Method releaseM = clazz.getDeclaredMethod("release");
        releaseM.invoke(scanner);

        return mediaUri;

    } catch (Throwable e) {
        e.printStackTrace();
        return null;
    }
}

From source file:com.elasticbox.jenkins.k8s.util.TestUtils.java

public static void clearEnv(String... keys) {
    try {//from   w  ww .ja v a2  s  .c o  m
        Class<?> processEnvironmentClass = Class.forName("java.lang.ProcessEnvironment");
        Field theEnvironmentField = processEnvironmentClass.getDeclaredField("theEnvironment");
        theEnvironmentField.setAccessible(true);
        Map<String, String> env = (Map<String, String>) theEnvironmentField.get(null);
        for (String key : keys) {
            env.remove(key);
        }
        Field theCaseInsensitiveEnvironmentField = processEnvironmentClass
                .getDeclaredField("theCaseInsensitiveEnvironment");
        theCaseInsensitiveEnvironmentField.setAccessible(true);
        Map<String, String> cienv = (Map<String, String>) theCaseInsensitiveEnvironmentField.get(null);
        for (String key : keys) {
            cienv.remove(key);
        }
    } catch (NoSuchFieldException e) {
        try {
            Class[] classes = Collections.class.getDeclaredClasses();
            Map<String, String> env = System.getenv();
            for (Class cl : classes) {
                if ("java.util.Collections$UnmodifiableMap".equals(cl.getName())) {
                    Field field = cl.getDeclaredField("m");
                    field.setAccessible(true);
                    Object obj = field.get(env);
                    Map<String, String> map = (Map<String, String>) obj;
                    for (String key : keys) {
                        map.remove(key);
                    }
                }
            }
        } catch (Exception e2) {
            e2.printStackTrace();
        }
    } catch (Exception e1) {
        e1.printStackTrace();
    }
}

From source file:com.sailing.hrm.common.util.ReflectionUtils.java

/**
 * ?, private/protected, ??getter./*www . ja  va  2  s. c o 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);
    }
    return result;
}

From source file:com.sunchenbin.store.feilong.core.lang.reflect.FieldUtil.java

/**
 * ?./*  www .  ja va2 s. c  o m*/
 *
 * @param <T>
 *            the generic type
 * @param owner
 *            the owner
 * @param fieldName
 *            the field name
 * @return 
 * @see java.lang.Object#getClass()
 * @see java.lang.Class#getField(String)
 * @see java.lang.reflect.Field#get(Object)
 * @since 1.4.0
 */
@SuppressWarnings("unchecked")
public static <T> T getFieldValue(Object owner, String fieldName) {
    try {
        Class<?> ownerClass = owner.getClass();
        Field field = ownerClass.getField(fieldName);
        return (T) field.get(owner);
    } catch (Exception e) {
        String formatMessage = Slf4jUtil.formatMessage("owner:[{}],fieldName:[{}]", owner, fieldName);
        LOGGER.error(formatMessage + e.getClass().getName(), e);
        throw new ReflectException(formatMessage, e);
    }
}

From source file:com.sunchenbin.store.feilong.core.lang.reflect.FieldUtil.java

/**
 * ???./*from w  ww . j a v a  2s . c o  m*/
 * 
 * <pre>
 * {@code
 * example1 :
 * 
 * FieldUtil.getStaticProperty("com.sunchenbin.store.feilong.core.io.ImageType", "JPG")
 *  :jpg
 * }
 * </pre>
 *
 * @param <T>
 *            the generic type
 * @param className
 *            ??,e.g com.sunchenbin.store.feilong.core.io.ImageType
 * @param fieldName
 *            ??
 * @return 
 * @see ClassUtil#loadClass(String)
 * @see java.lang.Class#getField(String)
 * @see java.lang.reflect.Field#get(Object)
 * 
 * @see org.apache.commons.lang3.reflect.FieldUtils#getField(Class, String)
 * @since 1.4.0
 */
@SuppressWarnings("unchecked")
public static <T> T getStaticFieldValue(String className, String fieldName) {
    try {
        Class<?> ownerClass = ClassUtil.loadClass(className);
        Field field = ownerClass.getField(fieldName);
        return (T) field.get(ownerClass);
    } catch (Exception e) {
        String formatMessage = Slf4jUtil.formatMessage("className:[{}],fieldName:[{}]", className, fieldName);
        LOGGER.error(formatMessage + e.getClass().getName(), e);
        throw new ReflectException(formatMessage, e);
    }
}

From source file:ml.shifu.shifu.util.ClassUtils.java

private static Object getFieldValue(Field field, Object instance)
        throws IllegalArgumentException, IllegalAccessException {
    field.setAccessible(true);//from  ww w.  j av a  2  s  . c o m
    return field.get(instance);
}

From source file:org.springmodules.cache.util.Reflections.java

/**
 * <p>//w  w w  .ja  v  a2 s.  c o  m
 * This method uses reflection to build a valid hash code.
 * </p>
 *
 * <p>
 * It uses <code>AccessibleObject.setAccessible</code> to gain access to
 * private fields. This means that it will throw a security exception if run
 * under a security manager, if the permissions are not set up correctly. It
 * is also not as efficient as testing explicitly.
 * </p>
 *
 * <p>
 * Transient members will not be used, as they are likely derived fields,
 * and not part of the value of the <code>Object</code>.
 * </p>
 *
 * <p>
 * Static fields will not be tested. Superclass fields will be included.
 * </p>
 *
 * @param obj
 *          the object to create a <code>hashCode</code> for
 * @return the generated hash code, or zero if the given object is
 *         <code>null</code>
 */
public static int reflectionHashCode(Object obj) {
    if (obj == null)
        return 0;

    Class targetClass = obj.getClass();
    if (Objects.isArrayOfPrimitives(obj) || Objects.isPrimitiveOrWrapper(targetClass)) {
        return Objects.nullSafeHashCode(obj);
    }

    if (targetClass.isArray()) {
        return reflectionHashCode((Object[]) obj);
    }

    if (obj instanceof Collection) {
        return reflectionHashCode((Collection) obj);
    }

    if (obj instanceof Map) {
        return reflectionHashCode((Map) obj);
    }

    // determine whether the object's class declares hashCode() or has a
    // superClass other than java.lang.Object that declares hashCode()
    Class clazz = (obj instanceof Class) ? (Class) obj : obj.getClass();
    Method hashCodeMethod = ReflectionUtils.findMethod(clazz, "hashCode", new Class[0]);

    if (hashCodeMethod != null) {
        return obj.hashCode();
    }

    // could not find a hashCode other than the one declared by java.lang.Object
    int hash = INITIAL_HASH;

    try {
        while (targetClass != null) {
            Field[] fields = targetClass.getDeclaredFields();
            AccessibleObject.setAccessible(fields, true);

            for (int i = 0; i < fields.length; i++) {
                Field field = fields[i];
                int modifiers = field.getModifiers();

                if (!Modifier.isStatic(modifiers) && !Modifier.isTransient(modifiers)) {
                    hash = MULTIPLIER * hash + reflectionHashCode(field.get(obj));
                }
            }
            targetClass = targetClass.getSuperclass();
        }
    } catch (IllegalAccessException exception) {
        // ///CLOVER:OFF
        ReflectionUtils.handleReflectionException(exception);
        // ///CLOVER:ON
    }

    return hash;
}

From source file:com.all.testing.AppContextTestUtils.java

public static void checkField(Object object, String name) throws Exception {
    log.debug("Checking... " + object.getClass().getName() + ":" + name);
    Field declaredField = object.getClass().getDeclaredField(name);
    declaredField.setAccessible(true);//  w  ww . jav  a2  s .  c o  m
    assertNotNull("Field " + name + " on " + object.getClass().getName() + " is null",
            declaredField.get(object));
}

From source file:com.fengduo.bee.commons.core.lang.BeanUtils.java

private static Unsafe getUnsafe() throws Exception {
    Field theUnsafe = Unsafe.class.getDeclaredField("theUnsafe");
    theUnsafe.setAccessible(true);//from   w w  w  .j a va  2s  .  co  m
    return (Unsafe) theUnsafe.get(null);
}

From source file:com.psiphon3.psiphonlibrary.WebViewProxySettings.java

@TargetApi(Build.VERSION_CODES.KITKAT)
@SuppressWarnings("rawtypes")
private static boolean setWebkitProxyKitKat(Context appContext, String host, int port) {
    System.setProperty("http.proxyHost", host);
    System.setProperty("http.proxyPort", port + "");
    System.setProperty("https.proxyHost", host);
    System.setProperty("https.proxyPort", port + "");
    try {/*from  w  ww .  j  a  v a2 s .co m*/
        Class applicationClass = Class.forName("android.app.Application");
        Field loadedApkField = applicationClass.getDeclaredField("mLoadedApk");
        loadedApkField.setAccessible(true);
        Object loadedApk = loadedApkField.get(appContext);
        Class loadedApkClass = Class.forName("android.app.LoadedApk");
        Field receiversField = loadedApkClass.getDeclaredField("mReceivers");
        receiversField.setAccessible(true);
        ArrayMap receivers = (ArrayMap) receiversField.get(loadedApk);
        for (Object receiverMap : receivers.values()) {
            for (Object receiver : ((ArrayMap) receiverMap).keySet()) {
                Class receiverClass = receiver.getClass();
                if (receiverClass.getName().contains("ProxyChangeListener")) {
                    Method onReceiveMethod = receiverClass.getDeclaredMethod("onReceive", Context.class,
                            Intent.class);
                    Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);

                    final String CLASS_NAME = "android.net.ProxyProperties";
                    Class proxyPropertiesClass = Class.forName(CLASS_NAME);
                    Constructor constructor = proxyPropertiesClass.getConstructor(String.class, Integer.TYPE,
                            String.class);
                    constructor.setAccessible(true);
                    Object proxyProperties = constructor.newInstance(host, port, null);
                    intent.putExtra("proxy", (Parcelable) proxyProperties);

                    onReceiveMethod.invoke(receiver, appContext, intent);
                }
            }
        }
        return true;
    } catch (ClassNotFoundException e) {
        MyLog.d("Exception setting WebKit proxy on KitKat through ProxyChangeListener: " + e.toString());
    } catch (NoSuchFieldException e) {
        MyLog.d("Exception setting WebKit proxy on KitKat through ProxyChangeListener: " + e.toString());
    } catch (IllegalAccessException e) {
        MyLog.d("Exception setting WebKit proxy on KitKat through ProxyChangeListener: " + e.toString());
    } catch (IllegalArgumentException e) {
        MyLog.d("Exception setting WebKit proxy on KitKat through ProxyChangeListener: " + e.toString());
    } catch (NoSuchMethodException e) {
        MyLog.d("Exception setting WebKit proxy on KitKat through ProxyChangeListener: " + e.toString());
    } catch (InvocationTargetException e) {
        MyLog.d("Exception setting WebKit proxy on KitKat through ProxyChangeListener: " + e.toString());
    } catch (InstantiationException e) {
        MyLog.d("Exception setting WebKit proxy on KitKat through ProxyChangeListener: " + e.toString());
    }
    return false;
}