1

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

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

I was going to take that approach, but my IDE is telling me that the method is deprecated
Yes, in Java 6 File.toURL() is deprecated. But the JavaDoc was also updated and suggests to use FILE.toURI().toURL() instead. I'll update the answer.
Thanks, it found it now

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.