简体   繁体   中英

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. 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.

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).

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.

Check whether the File actually sees the file as A4L just said,

Print the resulting URL, does that work in a browser?

Try

 f.toURI().toURL();

I find the solution, to load a jar file from the same package you need to do:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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