Unable to get DeclaredField "usr_paths " via java reflection 17.0.3

Viewed 75

I'm trying to get usr_paths, but the console gives an error that it can't find this field, what should I do?

public static void addDir(String s) throws IOException {
    try {
        Field field = ClassLoader.class.getDeclaredField("usr_paths"); // there's a error here !!
        field.setAccessible(true);
        String[] paths = (String[]) field.get(null);
        for (int i = 0; i < paths.length; i++) {
            if (s.equals(paths[i])) {
                return;
            }
        }
        String[] tmp = new String[paths.length + 1];
        System.arraycopy(paths, 0, tmp, 0, paths.length);
        tmp[paths.length] = s;
        field.set(null, tmp);
        System.setProperty("java.library.path", System.getProperty("java.library.path") + File.pathSeparator + s);
    } catch (IllegalAccessException e) {
        throw new IOException("Failed to get permissions to set library path");
    } catch (NoSuchFieldException e) {
        throw new IOException("Failed to get field handle to set library path");
    }
}
1 Answers

it doesn't exist but if it did the answer would be this:

Field field;
try {
    Method m = Class.class.getDeclaredMethod("getDeclaredFields0", boolean.class);
    m.setAccessible(true);
    for (Field f : (Field[]) m.invoke(ClassLoader.class, false)) {
        if (f.getName().equals("usr_paths")) {

            Method copy = Field.class.getDeclaredMethod("copy");
            forceAccessible(copy);

            field = (Field) copy.invoke(f);
        }
    }
} catch (Exception e) {}
Related