Home > Software engineering >  How to resolve "InaccessibleObjectException" of jdk16
How to resolve "InaccessibleObjectException" of jdk16

Time:01-17

I met a problem when I work for the framework: https://github.com/babyfish-ct/kimmer/

After I published the first version. I run the example, an exception raised

java.lang.reflect.InaccessibleObjectException: Unable to make protected final java.lang.Class java.lang.ClassLoader.defineClass(byte[],int,int) throws java.lang.ClassFormatError accessible: module java.base does not "opens java.lang" to unnamed module @74ea2410

This framework uses ASM to generate bytecode directly. It doesn't matter, using the higher-level cglib framework will encounter the same problem.

The problem is my framework(or cglib) wants to define new classes by runtime generated bytecode on EXISTING ClassLoader. To do this, I need to access protection-level methods under java.lang.ClassLoader through reflection, get the PROTECTED method and change its visibility, like this

private val DEFINE_CLASS = ClassLoader::class.java.getDeclaredMethod(
    "defineClass",
    ByteArray::class.java,
    Int::class.javaPrimitiveType,
    Int::class.javaPrimitiveType,
).also {
    it.isAccessible = true
}

Actually, I learned this trick from cglib's source code 10 years ago,this trick has been helping me.

Now, The JDK has become strict and this behavior is prohibited. I had to go and read the source code of the latest version of cglib. In ReflectUtils.java, I found cglib is trying to use "defineClass" of "sun.misc.Unsafe". Unfortunately, I can find that class but cannot find that method in "OpenJDK Runtime Environment Zulu16.30 19-CA".

I feel this problem is caused by jigsaw but I'm not jigsaw expert, so I left it open and let the user use "--illegal-access=permit".

How to resolve this problem and let my problems can work perfectly on latest JVM?

CodePudding user response:

Here is the relevant issue in that library, it may be helpful to find hacks that allow it to work for yours. https://github.com/cglib/cglib/issues/191.

Its usually on the library itself to add support for Java Modules.

CodePudding user response:

Resolved.

This problem can be resolved by https://github.com/jboss-javassist/javassist/blob/master/src/main/javassist/util/proxy/DefineClassHelper.java perfectly, I will use some of its code to fix this problem on next version

  •  Tags:  
  • Related