Question

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");
Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top