user668441
user668441

Reputation: 11

URLClassLoader not working

I want to load a file in the directory F:/badge-dao/bin/com/badge/dao/impl/, named BadgeDaoImpl. I am writing and testing the following code.

If I change the directory or the class name, it throws an exception. For the following code, which I suppose should work, it do not throw a classNotFoundException, but rather halts and take the control to EventTable's finally block.

Can you please tell me where I am getting it wrong.

URL[] urls = {new URL("file:/F:/badge-dao/bin/com/badge/dao/impl/")};

ClassLoader parentClassLoader = project.getClass().getClassLoader();

URLClassLoader classLoader = new URLClassLoader(urls, parentClassLoader);

selectedClass = classLoader.loadClass("BadgeDaoImpl");

Upvotes: 1

Views: 2139

Answers (1)

axtavt
axtavt

Reputation: 242786

Package name is a part of full class name, not classpath item, so you need the following:

URL[] urls = {new URL("file:/F:/badge-dao/bin")}; 
...
selectedClass = classLoader.loadClass("com.badge.dao.impl.BadgeDaoImpl"); 

In your original code classloader can find a file named BadgeDaoImpl.class in file:/F:/badge-dao/bin/com/badge/dao/impl/, but its full class name (com.badge.dao.impl.BadgeDaoImpl) doesn't match the requested one (BadgeDaoImpl), therefore classloader throws a NoClassDefFoundError. Since you are catching only ClassNotFoundException, it looks like control silently passes to the finally block. When you change folder or class names so that .class file can't be found, ClassNotFoundException is thrown as expected.

Upvotes: 4

Related Questions