Note that there are some explanatory texts on larger screens.

plurals
  1. POJava classloading running extremely slow?
    text
    copied!<p>I'm trying to load a java .class file dynamically and call it by reflection.</p> <p>I've got a class called Foo; it has an empty constructor and has one method called doit() which takes a String argument and returns a String. Also it reverses the String.</p> <p>Here is my code:</p> <pre><code> URL url = new URL("file://C:/jtest/"); URLClassLoader loader = new URLClassLoader(new URL[]{url}); Class&lt;?&gt; cl = loader.loadClass("Foo"); Constructor&lt;?&gt; cons = cl.getConstructor((Class[])null); Object ins = cons.newInstance(new Object[]{}); Method meth = cl.getDeclaredMethod("doit", String.class); Object ret = meth.invoke(ins, new Object[]{"!dlroW olleH"}); System.out.println((String)ret); </code></pre> <p>As expected this prints "Hello World!". However, it takes about <b>30 seconds</b> to complete. I know reflection is slow, but I expect it to be 10 ms or something.</p> <p>I'm using Eclipse with JRE 1.6.0_13, and I'm running Windows Vista.</p> <p>What am I doing wrong here?</p> <p>Thanks.</p> <p><b>Edit:</b> I've profiled the code, and all of its time is used in the third line(loadClass()). Everything else happens instantly.</p> <p><b>Edit:</b> I've put the code in a loop; the slow function somehow gets optimized and takes 30 seconds only on the first loop.</p> <p><b>Edit:</b> I've found the solution.</p> <p>Instead of: </p> <p><code>URL url = new URL("file://C:/jtest/");</code></p> <p>I changed it to:</p> <p><code>URL url = new URL("file:/C:/jtest/");</code></p> <p>Now it works perfectly. I don't know why it works, but I don't see how I (and 5 other people) could have missed that. Now I feel dumb..</p>
 

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