【发布时间】:2019-10-22 08:43:07
【问题描述】:
我正在尝试为我的程序制作一个类加载器/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)
【问题讨论】:
-
作为参考,类名大写(
modloader.java->ModLoader.java) -
URL 必须表示包含类文件的目录,而不是类文件本身。更复杂的是,它必须是正确的父目录,以允许根据其包名找到类文件。见this question…
-
以上评论解决了这个问题,非常感谢。
标签: java class classloader classnotfoundexception