Defining classes using Unsafe.defineClass without resolving dependencies

mastercooker :

Due to a requirement of my program, I am in the situation where I need to define multiple classes at runtime with a classloader of null (The bootstrap classloader).

This would normally be very easy using something like

unsafe.defineClass(name, bytes, 0, bytes.length, null, null);

This however does not work if I need to define say 5 different classes, each with references to each other. The JVM attempts to resolve these classes before they have been defined resulting in a NoClassDefFoundError.

Is there a way to prevent the JVM resolving classes when I define them with unsafe.defineClass?

If not is there potentially a way to do this using JNI?

This question is similar to this one, however the answers provided are not suitable as it includes defining the classes under a non null classloader.

apangin :

Unsafe.defineClass does not resolve classes, as specified in JVMS §5.4.3. The most of symbolic references in the constant pool remain unresolved.

The only dependencies that need to be satisfied at class definition time are

  1. the list of implemented interfaces;
  2. the superclass.

Any valid set of classes can be ordered in a way that

  • for any class or interface C being defined, all interfaces C implements are already defined before, and the superclass of C is also defined before.

This means, it is possible to define classes one by one, if done in the proper order. The above condition does not hold only in the case of circular inheritance (which is not valid anyway).

But make sure not to initialize classes or otherwise cause class resolution, until all of the referenced classes are defined.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=421989&siteId=1