jeudi 14 juillet 2022

How to resolve InaccessibleObjectException for Field.setAccessible in JDK 17?

With JDK 17, it's not possible anymore to make a field accessible using reflection, at least not for java.lang-classes. Following snippet:

final Process process = new ProcessBuilder().directory(new File("d:/temp")).command("cmd.exe").start();
final Field handleField = process.getClass().getDeclaredField("handle");
handleField.setAccessible(true);

fails with:

Exception in thread "main" java.lang.reflect.InaccessibleObjectException: Unable to make field private final long java.lang.ProcessImpl.handle accessible: module java.base does not "opens java.lang" to unnamed module @254989ff
    at java.base/java.lang.reflect.AccessibleObject.checkCanSetAccessible(AccessibleObject.java:354)
    at java.base/java.lang.reflect.AccessibleObject.checkCanSetAccessible(AccessibleObject.java:297)
    at java.base/java.lang.reflect.Field.checkCanSetAccessible(Field.java:178)
    at java.base/java.lang.reflect.Field.setAccessible(Field.java:172)

Is there a way to work around this problem?





Aucun commentaire:

Enregistrer un commentaire