How to load JAR files dynamically at Runtime?

前端 未结 20 3689
伪装坚强ぢ
伪装坚强ぢ 2020-11-21 05:15

Why is it so hard to do this in Java? If you want to have any kind of module system you need to be able to load JAR files dynamically. I\'m told there\'s a way of doing it b

20条回答
  •  没有蜡笔的小新
    2020-11-21 06:08

    Another version of the hackish solution from Allain, that also works on JDK 11:

    File file = ...
    URL url = file.toURI().toURL();
    URLClassLoader sysLoader = new URLClassLoader(new URL[0]);
    
    Method sysMethod = URLClassLoader.class.getDeclaredMethod("addURL", new Class[]{URL.class});
    sysMethod.setAccessible(true);
    sysMethod.invoke(sysLoader, new Object[]{url});
    

    On JDK 11 it gives some deprecation warnings but serves as a temporary solution those who use Allain solution on JDK 11.

提交回复
热议问题