1
 URLClassLoader child; try { child = new URLClassLoader(new URL[]{myJar.toURI().toURL()}, Test2.class.getClassLoader()); child.loadClass("com.bla.bla.StringUtilService"); } catch (MalformedURLException | ClassNotFoundException ex) { ex.printStackTrace(); } 

I am getting ClassNotFoundException in loadClass.

I have tried several variants of the code such as

URL[] urls = { new URL("jar:file:" + "E:\\Works\\Workspace\\JUnit_Proj\\client.jar"+"!/") }; URLClassLoader cl = URLClassLoader.newInstance(urls); 

But all results into ClassNotFoundException!

I have tried debugging in Eclipse, but the class loader instance is unable to load classes from the jar. The classes Vector is empty.

2
  • What is the type of myJar? Commented Nov 1, 2014 at 7:42
  • @Henry : java.io.File. Tried with JarFile as well. Commented Nov 1, 2014 at 10:17

2 Answers 2

1

Succeeded using different costructor of URLClassLoader.

  try { File jarFile = new File("D:\\Workspace\\Test\\Test.jar"); URLClassLoader loader = new URLClassLoader(new URL[]{jarFile.toURI().toURL()}); Class.forName("com.bla.bla.HelloWorld", true, loader); System.out.println("Success"); loader.close(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }  
Sign up to request clarification or add additional context in comments.

Comments

0

The class is a direct child of the dir in the url, so you need no package.

Try this without the package. Like this:

URLClassLoader child; try { child = new URLClassLoader(new URL[]{myJar.toURI().toURL()}, Test2.class.getClassLoader()); child.loadClass("StringUtilService"); } catch (MalformedURLException | ClassNotFoundException ex) { ex.printStackTrace(); } 

Also, try like this:

URLClassLoader child; try { child = new URLClassLoader(new URL[]{myJar.toURI().toURL()}, getClass().class.getClassLoader()); child.loadClass("StringUtilService"); } catch (MalformedURLException | ClassNotFoundException ex) { ex.printStackTrace(); } 

Solution from: ClassNotFoundException while loading a class from file with URLClassLoader

2 Comments

Anyone has successfully loaded classes from jars dynamically?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.