Java 类路径和类加载

Java classpath and classloading

我需要在 Java 的运行时加载一个 jar 文件,我有这段代码,但它没有加载任何 jar,我不知道如何加载,有人可以告诉我为什么吗?我有 JVM 8 和 NetBeans 8,目的是创建一个程序,可以将 jar 文件作为插件加载到 Windows。

package prueba.de.classpath;
import java.io.File;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;

public class PruebaDeClasspath {

    public static void main(String[] args) {
        try {
            Class.forName("PluginNumeroUno");
        } catch (ClassNotFoundException e) {
            System.out.println("Not Found");
        }

        try {
            URLClassLoader classLoader = ((URLClassLoader) ClassLoader
                    .getSystemClassLoader());
            Method metodoAdd = URLClassLoader.class.getDeclaredMethod("addURL",
                    new Class[]{URL.class});
            metodoAdd.setAccessible(true);


            File file = new File("plugins/PrimerPlugins.jar");

            URL url = file.toURI().toURL();
            System.out.println(url.toURI().toURL());

            metodoAdd.invoke(classLoader, new Object[]{url});
        } catch (Exception e) {
            e.printStackTrace();
        }

        try {
            Class.forName("PluginNumeroUno");
            System.out.println("ok");
        } catch (ClassNotFoundException e) {
            System.out.println("Not Found");
        }

    }

}

尝试创建新的 class 加载程序,而不是转换系统 class 加载程序。

删除这一行:

URLClassLoader classLoader = ((URLClassLoader) ClassLoader.getSystemClassLoader());

并创建新的加载器并按如下方式使用它:

File file = new File("plugins/PrimerPlugins.jar");
URLClassLoader classLoader = new URLClassLoader(new URL[]{file.toURI().toURL()},    
    PruebaDeClasspath.class.getClassLoader());
Class.forName("prueba.de.classpath.PluginNumeroUno", true, classLoader); //fully qualified!

请注意,要加载的 class 名称必须是完全限定的。

您也不必动态强制 addURL() 为 public。