Search code examples
javaswingdynamicclassloader

Java Dynamically Loading a class


I am attempting to load classes dynamically into a component. I am using a file chooser to select the .JAR file that will be loaded and then a option pane to get the name of the class.

I have trawled the internet looking for how to convert a java file to a URL in order to load it in URLClassLoader and I have come up with:

File myFile = filechooser.getSelectedFile();
String className = JOptionPane.showInputDialog(
    this, "Class Name:", "Class Name", JOptionPane.QUESTION_MESSAGE);

URL myUrl= null;
try {
    myUrl = myFile.toURL();
} catch (MalformedURLException e) {
}

URLClassLoader loader = new URLClassLoader(myUrl);
loader.loadClass(className);

I am now getting a 'cannot find symbol' error for loading the URL into the URLClassLoader


Solution

  • The constructor of URLClassLoader takes an array of URLs, not a single URL.