title: Define multiple classes at runtime using Unsafe.defineClass
body: <p>I am working on a REPL for a custom programming language of mine. It is implemented on top of the compiler, which it uses to generate the bytecode for the input and convert it to a <code>Class&lt;?&gt;</code> instance using the <code>sun.misc.Unsafe.defineClass(String, byte[], int, int, ClassLoader, ProtectionDomain)</code> method. The relevant code looks like this (irrelevant parts like exception handling omitted):</p>
  
  <pre><code>void compileAndLoad(List&lt;ICompilable&gt; compilables)
  {
      List&lt;Class&lt;?&gt;&gt; classes = ...;
      for (ICompilable c : compilables)
      {
          classes.add(compile(compilable));
      }
      for (Class&lt;?&gt; c : classes)
      {
          UNSAFE.ensureClassInitialized(c);
      }
  }
  
  // CLASS_LOADER = Enclosing.class.getClassLoader()
  // PROTECTION_DOMAIN = Enclosing.class.getClassLoader()
  
  Class&lt;?&gt; compile(ICompilable compilable)
  {
      byte[] bytecode = genBytecode(compilable);
      String name = compilable.getFullName() // e.g. 'foo.bar.Baz'
      return UNSAFE.defineClass(name, bytes, 0, bytes.length, CLASS_LOADER, PROTECTION_DOMAIN);
  }
  </code></pre>
  
  <p>Say the input requires multiple classes to be compiled and loaded.</p>
  
  <pre><code>&gt; class A { interface B { }; func b() = new B { /* anonymous class */ } }
  </code></pre>
  
  <p>The <code>compilables</code> list has the contents </p>
  
  <pre><code>[ repl.Result_0, repl.Result_0$A, repl.Result_0$A$0, repl.Result_0$A$B ]
  </code></pre>
  
  <p>The <code>repl.Result_0$A</code> class depends on the <code>repl.Result_0$A$0</code> (anonymous) class and the <code>repl.Result_0$B</code> class and references their names in the bytecode. When defining it using <code>Unsafe</code>, the following error will occur:</p>
  
  <pre><code>java.lang.NoClassDefFoundError: repl/Result_0$A$B
      at sun.misc.Unsafe.defineClass(Native Method)
      at MyClass.compile(MyClass.java:42)
      // ... snip
  Caused by: java.lang.ClassNotFoundException: repl.Result_0$A$B
      at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
      at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
      at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
      at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
      ... 9 more
  </code></pre>
  
  <p>I know this could be solved by reordering the list and defining <code>repl.Result_0$A$B</code> first, but that would not be a general solution since there can be references from <code>B -&gt; A</code> as well.</p>
  
  <p><strong>Is there a way to define and load multiple classes using <code>Unsafe.defineClass</code> without causing verification errors for unresolved classes?</strong></p>