How to load JAR files dynamically at Runtime?

前端 未结 20 3242
伪装坚强ぢ
伪装坚强ぢ 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:11

    The following solution is hackish, as it uses reflection to bypass encapsulation, but it works flawlessly:

    File file = ...
    URL url = file.toURI().toURL();
    
    URLClassLoader classLoader = (URLClassLoader)ClassLoader.getSystemClassLoader();
    Method method = URLClassLoader.class.getDeclaredMethod("addURL", URL.class);
    method.setAccessible(true);
    method.invoke(classLoader, url);
    

提交回复
热议问题