Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>If you used the custom <code>ClassLoader</code> exactly like in the linked answer it is not overriding the method <code>protected Class&lt;?&gt; loadClass(String name, boolean resolve)</code>. This implies that when the JVM is resolving dependencies it will still delegate to the parent class loader. And, of course, when it was not delegating to the parent <code>ClassLoader</code> it had the risk of missing some required classes.</p> <p>The easiest solution is to set up the right parent class loader. You are currently passing <code>Thread.currentThread().getContextClassLoader()</code> which is a bit strange as your main intention is that the delegation should <em>not</em> delegate to that loader but load the changed classes. You have to think about which class loaders exist and which to use and which not. E.g. if the class <code>Foo</code> is within the scope of your current code but you want to (re)load it with the new ClassLoader, <code>Foo.class.getClassLoader().getParent()</code> would be the right delegate parent for the new <code>ClassLoader</code>. Note that it might be <code>null</code> but this doesn’t matter as in this case it would use the bootstrap loader which is the correct parent then.</p> <p>Note that when you set up the right parent <code>ClassLoader</code> matching your intentions you don’t need that custom <code>ClassLoader</code> anymore. The default implementation (see <a href="http://docs.oracle.com/javase/7/docs/api/java/net/URLClassLoader.html" rel="noreferrer"><code>URLClassLoader</code></a>) already does the right thing. And with current Java versions it is <code>Closeable</code> making it even more suitable for dynamic loading scenarios.</p> <p>Here is a simple example of a class reloading:</p> <pre><code>import java.io.IOException; import java.net.URL; import java.net.URLClassLoader; public class ReloadMyClass { public static void main(String[] args) throws ClassNotFoundException, IOException { Class&lt;?&gt; myClass=ReloadMyClass.class; System.out.printf("my class is Class@%x%n", myClass.hashCode()); System.out.println("reloading"); URL[] urls={ myClass.getProtectionDomain().getCodeSource().getLocation() }; ClassLoader delegateParent = myClass.getClassLoader().getParent(); try(URLClassLoader cl=new URLClassLoader(urls, delegateParent)) { Class&lt;?&gt; reloaded=cl.loadClass(myClass.getName()); System.out.printf("reloaded my class: Class@%x%n", reloaded.hashCode()); System.out.println("Different classes: "+(myClass!=reloaded)); } } } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload