Example usage for java.lang.reflect Field setAccessible

List of usage examples for java.lang.reflect Field setAccessible

Introduction

In this page you can find the example usage for java.lang.reflect Field setAccessible.

Prototype

@Override
@CallerSensitive
public void setAccessible(boolean flag) 

Source Link

Usage

From source file:com.meiah.core.util.ReflectionUtils.java

/**
 * ?, ?DeclaredField,    ?.//from   ww  w .j  a  v a2s.  c o  m
 * 
 * ?Object?, null.
 */
public static Field getAccessibleField(final Object obj, final String fieldName) {
    for (Class<?> superClass = obj.getClass(); superClass != Object.class; superClass = superClass
            .getSuperclass()) {
        try {
            Field field = superClass.getDeclaredField(fieldName);
            field.setAccessible(true);
            return field;
        } catch (NoSuchFieldException e) {//NOSONAR
            // Field??,?
        }
    }
    return null;
}

From source file:com.alvermont.terraj.fracplanet.io.JarLibraryLoader.java

/**
 * Adds our extraction path to the system library path.
 *
 * @throws NoSuchFieldException if there is a reflection error
 * @throws IllegalAccessException if there is an access error during reflection
 *//*from  w  w  w  . j  av a2  s .  c  o  m*/
public static void setupPath() throws NoSuchFieldException, IllegalAccessException {
    String dir = System.getProperty("user.home");

    dir = new File(dir).getPath();

    String newLibPath = dir + File.pathSeparator + System.getProperty("java.library.path");
    System.setProperty("java.library.path", newLibPath);

    Field fieldSysPath = ClassLoader.class.getDeclaredField("sys_paths");
    fieldSysPath.setAccessible(true);
    if (fieldSysPath != null) {
        fieldSysPath.set(System.class.getClassLoader(), null);
    }

    log.debug("Lib path: " + newLibPath);
}

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

/**
 * ?, ?DeclaredField,    ?.// www  .ja v a2  s.c o m
 * <p/>
 * ?Object?, null.
 */
public static Field getAccessibleField(final Object obj, final String fieldName) {
    Validate.notNull(obj, "object can't be null");
    Validate.notEmpty(fieldName, "fieldName can't be blank");
    for (Class<?> superClass = obj.getClass(); superClass != Object.class; superClass = superClass
            .getSuperclass()) {
        try {
            Field field = superClass.getDeclaredField(fieldName);
            field.setAccessible(true);
            return field;
        } catch (NoSuchFieldException e) {//NOSONAR
            // Field??,?
        }
    }
    return null;
}

From source file:com.sixt.service.framework.servicetest.helper.DockerComposeHelper.java

@SuppressWarnings("unchecked")
private static void setEnv(Map<String, String> newEnv) {
    try {/*from w ww .j  a v a  2  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);
        env.putAll(newEnv);
        Field theCaseInsensitiveEnvironmentField = processEnvironmentClass
                .getDeclaredField("theCaseInsensitiveEnvironment");
        theCaseInsensitiveEnvironmentField.setAccessible(true);
        Map<String, String> cienv = (Map<String, String>) theCaseInsensitiveEnvironmentField.get(null);
        cienv.putAll(newEnv);
    } 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;
                    map.clear();
                    map.putAll(newEnv);
                }
            }
        } catch (Exception e2) {
            e2.printStackTrace();
        }
    } catch (Exception e1) {
        e1.printStackTrace();
    }
}

From source file:com.ocs.dynamo.test.MockUtil.java

/**
 * Registers all fields that are annotated with "@Mock" as beans in the Spring context
 * //from  ww w .j a va  2  s  .co m
 * @param factory
 * @param subject
 * @param clazz
 */
public static void registerMocks(ConfigurableListableBeanFactory factory, Object subject, Class<?> clazz) {
    try {
        Field[] fields = clazz.getDeclaredFields();
        for (Field field : fields) {
            field.setAccessible(true);
            if (field.getAnnotation(Mock.class) != null) {
                factory.registerSingleton(field.getName(), field.get(subject));
            }
        }
        if (clazz.getSuperclass() != null) {
            registerMocks(factory, subject, clazz.getSuperclass());
        }
    } catch (Exception e) {
        throw new OCSRuntimeException(e.getMessage(), e);
    }
}

From source file:nu.yona.server.test.util.JUnitUtil.java

public static Field getAccessibleField(Class<?> clazz, String fieldName) {
    Field field = Arrays.asList(clazz.getDeclaredFields()).stream().filter(f -> f.getName().equals(fieldName))
            .findAny().orElseThrow(() -> new IllegalStateException("Cannot find field '" + fieldName + "'"));
    field.setAccessible(true);
    return field;
}

From source file:ca.psiphon.tunneledwebview.WebViewProxySettings.java

@TargetApi(Build.VERSION_CODES.KITKAT) // for android.util.ArrayMap methods
@SuppressWarnings("rawtypes")
private static boolean setWebkitProxyLollipop(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   ww w.j a v  a 2 s.  co m
        Class applictionClass = Class.forName("android.app.Application");
        Field mLoadedApkField = applictionClass.getDeclaredField("mLoadedApk");
        mLoadedApkField.setAccessible(true);
        Object mloadedApk = mLoadedApkField.get(appContext);
        Class loadedApkClass = Class.forName("android.app.LoadedApk");
        Field mReceiversField = loadedApkClass.getDeclaredField("mReceivers");
        mReceiversField.setAccessible(true);
        ArrayMap receivers = (ArrayMap) mReceiversField.get(mloadedApk);
        for (Object receiverMap : receivers.values()) {
            for (Object receiver : ((ArrayMap) receiverMap).keySet()) {
                Class clazz = receiver.getClass();
                if (clazz.getName().contains("ProxyChangeListener")) {
                    Method onReceiveMethod = clazz.getDeclaredMethod("onReceive", Context.class, Intent.class);
                    Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
                    onReceiveMethod.invoke(receiver, appContext, intent);
                }
            }
        }
        return true;
    } catch (ClassNotFoundException e) {
    } catch (NoSuchFieldException e) {
    } catch (IllegalAccessException e) {
    } catch (NoSuchMethodException e) {
    } catch (InvocationTargetException e) {
    }
    return false;
}

From source file:com.gargoylesoftware.htmlunit.httpclient.HtmlUnitSSLConnectionSocketFactory.java

private static void setEmptyHostname(final HttpHost host) {
    try {//from w w w  . j a  v  a2s  .c om
        final Field field = HttpHost.class.getDeclaredField("hostname");
        field.setAccessible(true);
        field.set(host, "");
    } catch (final Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:Main.java

/**
 * Look up a field in a class and set it to accessible. The result is cached.
 * If the field was not found, a {@link NoSuchFieldError} will be thrown.
 *///from w  ww .  j ava2 s  .c o m
public static Field findField(Class<?> clazz, String fieldName) {
    StringBuilder sb = new StringBuilder(clazz.getName());
    sb.append('#');
    sb.append(fieldName);
    String fullFieldName = sb.toString();

    if (fieldCache.containsKey(fullFieldName)) {
        Field field = fieldCache.get(fullFieldName);
        if (field == null)
            throw new NoSuchFieldError(fullFieldName);
        return field;
    }

    try {
        Field field = findFieldRecursiveImpl(clazz, fieldName);
        field.setAccessible(true);
        fieldCache.put(fullFieldName, field);
        return field;
    } catch (NoSuchFieldException e) {
        fieldCache.put(fullFieldName, null);
        throw new NoSuchFieldError(fullFieldName);
    }
}

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

/**
 * Get the value of the PK field//from www  . j  ava  2s .c  om
 *
 * @param <T>
 * @param entity
 * @return PK value or a String key for composite PKs
 */
public static <T extends BaseEntity> String getPKFieldValue(T entity) {
    String value = null;
    Field field = getPKField(entity);
    if (field != null) {
        field.setAccessible(true);
        Object pkValue;
        try {
            pkValue = field.get(entity);
            if (pkValue != null) {
                value = pkValue.toString();
            }
        } catch (IllegalArgumentException | IllegalAccessException ex) {
            throw new OpenStorefrontRuntimeException("Unable to get value on " + entity.getClass().getName(),
                    "Check entity passed in.");
        }
    } else {
        throw new OpenStorefrontRuntimeException("Unable to find PK for enity: " + entity.getClass().getName(),
                "Check entity passed in.");
    }
    return value;
}