[Solved] Java 9 reflection error: java.lang.reflect.InaccessibleObjectException

Java 9 reflection error

Problem solving

Question

when writing JavaFX, perform the HTTP request database login operation, and convert the returned JSON string into a class object. The following code always reports an error.

// json string to class object
JavaType javaType;
ResponseBean<T> data = new ObjectMapper().readValue(json, javaType);

the following errors are reported:

java.lang.reflect.InaccessibleObjectException: Unable to make protected cc.nsurl.bean.ResponseBean() accessible: module cc.nsurl.controllers does not "opens cc.nsurl.bean" to module com.fasterxml.jackson.databind

if you can’t open the class, you can’t reflect.

Solution:

Add the file module-info.java to the JavaFX project. The overall project structure is as follows:

-- src
   -- main
       -- java
          -- module-info.java

Configure in this java file:

module cc.nsurl.controllers {
    // Classes that require reflection opens Self-written classes to third-party libraries
    opens cc.nsurl.controllers to javafx.fxml;
    opens cc.nsurl.bean to com.fasterxml.jackson.databind;
    exports cc.nsurl.controllers;
}

Read More: