2

I have the following code snippet

URL url = new File("c:/work/projects/jars/").toURI().toURL();
URL[] urls = new URL[]{url};
URLClassLoader child = new URLClassLoader(urls, this.getClass().getClassLoader());
URL res = child.findResource("temp.txt");
cls = child.loadClass("com.foo.adapter.sample.PluginImpl");

The jars folder contains a text file "temp.txt" and a jar file which contiains the PluginImpl class. The resource is loaded but the class is not. When I extract the jar's contents to the folder the class is getting loaded. Where am I going wrong?

mihirg
  • 915
  • 2
  • 13
  • 28

1 Answers1

2

You have to add the JAR itself to the classpath. The JVM differentiates between resources and JARs. This should work:

URL url1 = new File("c:/work/projects/jars/").toURI().toURL(); // resources
URL url2 = new File("c:/work/projects/jars/myjar.jar").toURI().toURL(); // jar
URL[] urls = new URL[]{url1, url2};
home
  • 12,468
  • 5
  • 46
  • 54
  • Is there any way where I give a directory path and all jars and resources in that path available to the class loader? – mihirg Jul 10 '11 at 06:12
  • @chimanrao: see this question: http://stackoverflow.com/questions/219585/setting-multiple-jars-in-java-classpath. Maybe this helps, otherwise scan your directory and build the URL array – home Jul 10 '11 at 07:55