1

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");
Nick
  • 25,026
  • 7
  • 51
  • 83
user668441
  • 11
  • 3
  • 3
    Are you sure that `bin` is *not* your real classpath directory and you really want to load `com.badge.dao.impl.BadgeDaoImpl`? Also, what `finally` block are you talking about? – Bombe Mar 23 '11 at 09:05
  • Yes, I am working on a eclipse plugin, and it is not the bin of the plugin rather, the bin folder of the project selected in the workspace. So, I suppose it is not the classpath included in the default classloader, but I do not have lot of experience with ClassLoading. – user668441 Mar 23 '11 at 09:16

1 Answers1

4

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.

axtavt
  • 239,438
  • 41
  • 511
  • 482