0

I'm trying to make a classloader/modloader for my program. So far I have this loader:

    // methodTB - swing text field for method
    // classTB - swing text field for class
    // classCB - swing check box for default class (which is the file name)

    // Grab the URL of the file
    URL url = file.toURI().toURL();
    URL[] urls = new URL[]{url};
    // Make a ClassLoader
    ClassLoader cl = new URLClassLoader(urls);
    // If the class name = file name
    if (classCB.isSelected()) {
        // Get the name of the class
        className = file.getName();
        // Remove the file extension
        className = className.substring(0, className.lastIndexOf('.'));
    }
    // Else
    else {
        // Grab directly from the TB
        className = classTB.getText();
    }
    // Load it
    Class cls = cl.loadClass(className);
    Method method = cls.getDeclaredMethod(methodTB.getText());
    Object instance = cls.newInstance();
    Object result = method.invoke(instance);

This works for classes that already exist within the program, however, when trying to load other classes, the following exception pops up:

java.lang.ClassNotFoundException: example
   at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
   at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
   at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
   at modloader.lambda$menu$1(modloader.java:116) <4 internal calls>
   at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252) <31 internal calls>

Is there any way I can load classes that are outside of the program?

(For context, here's the full code)

ggtylerr
  • 31
  • 4
  • For reference, class names are capitalized (`modloader.java` -> `ModLoader.java`) – Benjamin Urquhart Jun 06 '19 at 20:54
  • 1
    The URL must denote the directory containing the class files, not the class file itself. To make matters more complicated, it must be the right parent directory, to allow finding the class file according to its package name. See [this question](https://stackoverflow.com/q/39360914/2711488)… – Holger Jun 07 '19 at 15:05
  • Above comment solved the issue, thank you alot. – ggtylerr Jun 08 '19 at 08:38

1 Answers1

0

If my understanding is correct, you want to load the class which is outside of classpath. You have to write like this.

URL jarFilesUrl = new URL("file:/" + "dir containing jar files" + "/"); 
URLClassLoader cl = new URLClassLoader(new URL[] {jarFilesUrl},getClass().class.getClassLoader());
CustomClass customObj = (CustomClass) cl.loadClass("com.pkg.CustomClass").newInstance();

In this case, there should be a directory which may contain some jar files.

Sambit
  • 7,625
  • 7
  • 34
  • 65