简体   繁体   中英

ClassNotFound With URLClassLoader

I currently have the following directory tree structure:

CLASSES  
  -> ClassOne  
     ->package
        -> my
           ->App.class

I would like to load the App.class from my local drive. I looked around, particularly stackoverflow, and most seem to suggest that I should use the URLClassLoader.

In order to do this, I used this following code:

However, I get a ClassNotFoundError. Can anybody help me please.

 String url = "file://" + classOneFolder.getAbsolutePath(); //Where classesFolder is a File representing the ClassOne directory

 URL[] urls = {new URL(url)};
 urlClassLoader = URLClassLoader.newInstance(urls);                    

 //class loader needs the fully classified class name. Therefore:
 Class appClass = urlClassLoader.loadClass("package.my.App");

I would suggest you use classOneFolder.toURI().toURL() instead of building the URL yourself as a String and then recreate a URL from it. On some systems (like Windows) you need to add another slash in front on the absolute filename for a valid URL. Using File.toURI() .toURL() should always build a correct URL.

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