简体   繁体   English

Java动态加载jar

[英]Java load dynamically jar

I found many discussions about the argument but no solution works for me. 我找到了很多关于该论点的讨论,但没有解决方案对我有用。

I want create a simple plugin (jar) that contains also the jdbc driver in order to works. 我想创建一个也包含jdbc驱动程序的简单插件(jar),以便工作。 This plugin in then is used inside a larger app. 然后,此插件将在更大的应用程序中使用。

If I create a very simple main as this: 如果我这样创建一个非常简单的主体:

public static void main(String[] args) {
        URL url;
        try {
            File f = new File("mysql-connector-java-5.1.22.jar");
            URLClassLoader child = new URLClassLoader(new URL[] { f.toURL() }, Plugin.class.getClassLoader());
            Class classToLoad = Class.forName("com.mysql.jdbc.Driver", true, child);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

I've always this exception: 我总是有这样的例外:

java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
at java.net.URLClassLoader$1.run(URLClassLoader.java:372)
at java.net.URLClassLoader$1.run(URLClassLoader.java:361)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:360)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:340)

So seems that the Class.forName is not able to found the jar that is in the same package of my Plugin class. 似乎Class.forName无法找到与我的Plugin类相同的程序包中的jar。

I tried many solutions but noone works for me. 我尝试了许多解决方案,但没有人为我工作。 Is possibile to load the jar without refers directly to it (it in the same package of the main class). 可以在不直接引用jar的情况下加载jar(在主类的同一包中)。

Thanks 谢谢

I don't think the location of the jar file should be relative to your Package, more likely in the current working directory from which you launched the app. 我认为jar文件的位置不应该与您的Package有关,更不可能在您启动该应用程序的当前工作目录中。

Check whether the File actually sees the file as A4L just said, 检查文件是否实际上将文件视为A4L,

Print the resulting URL, does that work in a browser? 打印生成的URL,在浏览器中是否可以使用?

Try 尝试

 f.toURI().toURL();

I find the solution, to load a jar file from the same package you need to do: 我找到了解决方案,可以从您需要执行的相同包中加载jar文件:

URL url = YourClass.class.getResource("mysql-connector-java-5.1.22.jar");
URLClassLoader child = new URLClassLoader(new URL[] { url }, YourClass.class.getClassLoader());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM