1

There are several posts about how to add jar-file to classpath at runtime by following idea: - get current system classpath; - suppose it is URLClassLoader; - use reflection to set access for protected addURL method; - use mentioned method to add url to classpath.

Here is an example: Adding files to java classpath at runtime

Because of 2 and 3 steps this looks like "nasty hack".

How could I extend URLClassLoader and set it as a current? I am bit confused with classloaders and tried the following:

public static void main(String... args) {
    URLClassLoader loader = new URLClassLoader(new URL[]{new URL("file:jxl.jar")});
    System.out.println(loader.loadClass("jxl.Workbook"));
    Thread.currentThread().setContextClassLoader(loader);
    System.out.println(Class.forName("jxl.Workbook"));
} // main

I get ClassNotFoundException on the fourth line, while second works ok. (why it is so, by the way?)

Community
  • 1
  • 1
Rodion Gorkovenko
  • 2,670
  • 3
  • 24
  • 37

1 Answers1

2

The Class.forName method uses the "defining class loader of the current class," not the thread context classloader. In your case the ClassLoader that Class.forName will use is the one that loaded your application, i.e. the system class loader. This is a class loader that looks for resources in the class path.

Joni
  • 108,737
  • 14
  • 143
  • 193
  • Ah... thank you... I forgot of it. But what if I change fourth line to: System.out.println(jxl.Workbook.class); - surely I should provide import jxl.* while compilation - it would not work on runtime either. – Rodion Gorkovenko Feb 02 '12 at 07:19
  • In that case you would need to have jxl.Workbook in the classpath to compile. If you tried to execute without jxl.Workbook the JVM would throw a NoClassDefFoundError when loading your class – Joni Feb 02 '12 at 07:25
  • Oh, you are right, it is different kind of error. I think it is bit clearer now. Thank you for your explanation! – Rodion Gorkovenko Feb 02 '12 at 07:39