java - 如何在程序之外加载类?

标签 java class classloader classnotfoundexception

我正在尝试为我的程序制作一个类加载器/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)

最佳答案

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

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 文件。

关于java - 如何在程序之外加载类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56484192/

相关文章:

jdbc - Class.forName(Driver.class)

java - 使用 ClassLoader 后类不可用

c++ - 类(class)的私有(private)成员在我的类(class)实例化期间发生了变化,即使他们不应该

java - 阻止对 Jetty 服务器的请求

java - 解析 withinMiles 首先返回最近的

java - 如何关闭 httpclient 中 log4j 的警告消息?

javascript - 使用 es6 类语法创建一个将 Function 对象创建为实例的类

php - 扩展 MySQLi 类

java - 以编程方式更改 OSGi 包导入

java - 他们有什么方法可以将 Eclipse 中的两个反斜杠消除为一吗