gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 04:45:46 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com