How to load JAR files dynamically at Runtime?

前端 未结 20 3801
伪装坚强ぢ
伪装坚强ぢ 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 05:55

    While most solutions listed here are either hacks (pre JDK 9) hard to configure (agents) or just don't work anymore (post JDK 9) I find it really surprising that nobody mentioned a clearly documented method.

    You can create a custom system class loader and then you're free to do whatever you wish. No reflection required and all classes share the same classloader.

    When starting the JVM add this flag:

    java -Djava.system.class.loader=com.example.MyCustomClassLoader
    

    The classloader must have a constructor accepting a classloader, which must be set as its parent. The constructor will be called on JVM startup and the real system classloader will be passed, the main class will be loaded by the custom loader.

    To add jars just call ClassLoader.getSystemClassLoader() and cast it to your class.

    Check out this implementation for a carefully crafted classloader. Please note, you can change the add() method to public.

提交回复
热议问题