【问题标题】:How do I load classes outside of the program?如何在程序之外加载类?
【发布时间】: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


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-01-30
    • 1970-01-01
    • 1970-01-01
    • 2011-01-11
    • 2011-09-27
    • 1970-01-01
    • 2012-10-29
    • 2018-07-08
    相关资源
    最近更新 更多