简体   繁体   中英

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");

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM