lundi 21 août 2023

Why do exceptions occur when using reflection in jdk17?

I need to obtain the value in the current ThreadLocal through reflection

but there is an exception about "*module java.base does not "opens java.lang" to unnamed module *"

And after adding the following configuration to the jvm startup parameters, the exception was resolved

--add-opens
java.base/java.lang=ALL-UNNAMED
--add-opens
java.base/java.lang.ref=ALL-UNNAMED

My questions :
1. Why the objects defined by myself, no error reported

  public class Record implements Serializable {
  private String name;
  // ....
  }

2. Is there any other way besides adding startup parameters in the jvm


java -version

java version "17.0.3" 2022-04-19 LTS
Java(TM) SE Runtime Environment (build 17.0.3+8-LTS-111)
Java HotSpot(TM) 64-Bit Server VM (build 17.0.3+8-LTS-111, mixed mode, sharing)

My Code

public class TT {
    public static void main(String[] args) throws Exception {

        Thread thread = Thread.currentThread();
        Field threadLocalsField = Thread.class.getDeclaredField("threadLocals");
        threadLocalsField.setAccessible(true);
        Object threadLocals = threadLocalsField.get(thread);
        System.out.println(threadLocals);
    }

}

the detail error

Exception in thread "main" java.lang.reflect.InaccessibleObjectException: Unable to make field java.lang.ThreadLocal$ThreadLocalMap java.lang.Thread.threadLocals accessible: module java.base does not "opens java.lang" to unnamed module @327471b5
    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)
    at com.moan.message.base.remote.service.helper.TT.main(TT.java:19)

One useful way: add vm option

--add-opens
java.base/java.lang=ALL-UNNAMED
--add-opens
java.base/java.lang.ref=ALL-UNNAMED




Aucun commentaire:

Enregistrer un commentaire