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:io.apiman.manager.api.migrator.DataMigratorTest.java

/**
 * @param version/*from  ww w .  ja v a  2  s  .co m*/
 * @param versionString
 * @throws Exception
 */
private static void setVersion(Version version, String versionString) throws Exception {
    Field field = version.getClass().getDeclaredField("versionString");
    field.setAccessible(true);
    field.set(version, versionString);

    field = version.getClass().getDeclaredField("versionDate");
    field.setAccessible(true);
    field.set(version, new Date().toString());
}

From source file:Main.java

public static Object getField(Field field, Object source) {
    boolean accessible = field.isAccessible();
    field.setAccessible(true);
    Object result = null;/*from   w w w. ja v a2 s .  c  om*/
    try {
        result = field.get(source);
    } catch (IllegalAccessException e) {
        // ignore
    }
    field.setAccessible(accessible);
    return result;
}

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

private static void getProperties(Class<?> klazz, String path, Deque<Field> fieldChain) {
    for (Field f : klazz.getDeclaredFields()) {
        f.setAccessible(true);
        JsonProperty jsonProperty = f.getAnnotation(JsonProperty.class);
        if (jsonProperty != null) {
            fieldChain.push(f);//from ww  w.j a va2s.c om
            // If the inspected type has nested @JsonProperty annotations, we need to inspect it
            if (hasJsonPropertyAnnotation(f)) {
                getProperties(f.getType(), f.getName() + ".", fieldChain); // Add "." when traversing into new object.
            } else { // Otherwise, just assume it's simple as the best we can do is #toString
                List<Field> fieldList = new ArrayList<>(fieldChain);
                Collections.reverse(fieldList);
                STANDARD_CLAIMS_FIELD_MAP.put(path + jsonProperty.value(), fieldList);
                fieldChain.pop(); // Pop, as we have now reached end of this chain.
            }
        }
    }
}

From source file:org.schedulesdirect.api.utils.HttpUtils.java

static public Header[] scrapeHeaders(Request r) {
    try {//from  w  w w . j a  v a2 s  .  c  o  m
        Field f = r.getClass().getDeclaredField("request");
        f.setAccessible(true);
        HttpRequestBase req = (HttpRequestBase) f.get(r);
        return req.getAllHeaders();
    } catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException e) {
        LOG.error("Error accessing request headers!", e);
        return new Header[0];
    }
}

From source file:utils.ReflectionService.java

public static Map createClassModel(Class clazz, int maxDeep) {
    Map map = new HashMap();
    for (Field field : clazz.getDeclaredFields()) {
        field.setAccessible(true);
        String key = field.getName();
        try {//from   ww  w.  ja  va2 s .  co  m
            Class<?> type;
            if (Collection.class.isAssignableFrom(field.getType())) {
                ParameterizedType collectionType = (ParameterizedType) field.getGenericType();
                type = (Class<?>) collectionType.getActualTypeArguments()[0];
            } else {
                type = field.getType();
            }

            //            System.out.println(key + " ReflectionResource.createClassModel ==== putting type: " + field.getType().getName() + ", static: "
            //            + Modifier.isStatic(field.getModifiers()) + ", enum: " + type.isEnum() + ", java.*: " + type.getName().startsWith("java"));

            if (Modifier.isStatic(field.getModifiers())) {
                continue;
            } else if (type.isEnum()) {
                map.put(key, Enum.class.getName());
            } else if (!type.getName().startsWith("java") && !key.startsWith("_") && maxDeep > 0) {
                map.put(key, createClassModel(type, maxDeep - 1));
            } else {
                map.put(key, type.getName());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    return map;
}

From source file:name.martingeisse.esdk.simulation.lwjgl.NativeLibraryHelper.java

/**
 * Extracts LWJGL libraries to a folder and 
 * @throws Exception on errors//from  w ww .  j a  v a2s  . c  o  m
 */
public static void prepareNativeLibraries() throws Exception {

    // Unfortunately, Java is also too stupid to create a temp directory...
    tempFolder = File.createTempFile("miner-launcher-", "");
    deleteRecursively(tempFolder);
    tempFolder.mkdir();
    logger.debug("temp: " + tempFolder.getAbsolutePath());

    // detect which set of native libraries to load, then extract the files
    resourcePath = OperatingSystemSelector.getHostOs().getNativeLibraryPath();
    logger.debug("native library path: " + resourcePath);
    for (String fileName : OperatingSystemSelector.getHostOs().getNativeLibraryFileNames()) {
        extractFile(fileName);
    }

    // make Java use our libraries
    System.setProperty("java.library.path", tempFolder.getAbsolutePath());
    final Field fieldSysPath = ClassLoader.class.getDeclaredField("sys_paths");
    fieldSysPath.setAccessible(true);
    fieldSysPath.set(null, null);

}

From source file:Main.java

/**
 * Forces the appearance of a menu in the given context.
 * @param ctx//  w ww  .  j a  v  a  2s.c  om
 */
public static void showMenu(Context ctx) {
    try {
        ViewConfiguration config = ViewConfiguration.get(ctx);
        Field menuKeyField = ViewConfiguration.class.getDeclaredField("sHasPermanentMenuKey");

        if (menuKeyField != null) {
            menuKeyField.setAccessible(true);
            menuKeyField.setBoolean(config, false);
        }
    } catch (Exception e) {
    }
}

From source file:Main.java

/**
 * Returns a reference to the thread's threadLocals field
 * /*from ww w. j  av  a 2s. c om*/
 * @param t
 * @return
 * @throws NoSuchFieldException 
 * @throws SecurityException 
 * @throws IllegalAccessException 
 * @throws IllegalArgumentException 
 */
private static Object getMap(Thread t)
        throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException {
    Field threadLocalField = Thread.class.getDeclaredField("threadLocals");
    threadLocalField.setAccessible(true);
    return threadLocalField.get(t);
}

From source file:com.picklecode.popflix.App.java

public static void setLibraryPath(String path) throws Exception {
    System.setProperty("java.library.path", path);

    //set sys_paths to null so that java.library.path will be reevalueted next time it is needed
    final Field sysPathsField = ClassLoader.class.getDeclaredField("sys_paths");
    sysPathsField.setAccessible(true);
    sysPathsField.set(null, null);//from   w  ww  . j a  v a 2s  .  c  om
}

From source file:Main.java

/**
 * This method will iterate over all the fields on an object searching for declared fields defined as
 * Collection, List, Set, Map type.  If those fields are null they will be set to empty unmodifiable
 * instances.  If those fields are not null then it will force them to be unmodifiable.
 *
 * This method does not handle nested types.
 *
 * @param o the object to modify.  a null object will do nothing.
 *///from   ww w . j  a va2s  .co m
public static void makeUnmodifiableAndNullSafe(Object o) throws IllegalAccessException {
    if (o == null) {
        return;
    }

    Class<?> targetClass = o.getClass();
    for (Field f : targetClass.getDeclaredFields()) {
        f.setAccessible(true);
        try {
            if (f.getType().isAssignableFrom(List.class)) {
                f.set(o, unmodifiableListNullSafe((List<?>) f.get(o)));
            } else if (f.getType().isAssignableFrom(Set.class)) {
                f.set(o, unmodifiableSetNullSafe((Set<?>) f.get(o)));
            } else if (f.getType().isAssignableFrom(Collection.class)) {
                f.set(o, unmodifiableCollectionNullSafe((Collection<?>) f.get(o)));
            } else if (f.getType().isAssignableFrom(Map.class)) {
                f.set(o, unmodifiableMapNullSafe((Map<?, ?>) f.get(o)));
            }
        } finally {
            f.setAccessible(false);
        }
    }
}