如何在程序外部加载类?

时间:2019-06-06 19:48:44

标签: java class classloader classnotfoundexception

我正在尝试为我的程序制作一个classloader / modloader。到目前为止,我有这个装载程序:

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

这适用于程序中已经存在的类,但是,当尝试加载其他类时,会弹出以下异常:

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>

有什么办法可以加载程序外部的类?

(对于上下文,here's the full code

1 个答案:

答案 0 :(得分:0)

如果我的理解是正确的,那么您想加载类路径之外的类。你必须这样写。

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

在这种情况下,应该有一个目录,其中可能包含一些jar文件。