Load jar dynamically

前端 未结 1 510
旧时难觅i
旧时难觅i 2021-01-27 06:23

In my java application, I read a jar file (packaged with Maven shade plugin) into a bytestream. In the jar there is a entrypoint class defined in POM.xml

         


        
1条回答
  •  时光说笑
    2021-01-27 06:52

    The easiest way to do this is to use a URLClassLoader instead of trying to do this from scratch from a byte stream. You can always write the .jar out to a temporary file and create a URL to that.

    The code would look something like:

    URLClassLoader loader = new URLClassLoader(
        new URL[] {new URL("file://...")},
        Thread.currentThread().getContextClassLoader());
    
    loader.loadClass("com.mycompany.TheEntryPoint");
    

    You can also detect the main class name (or invoke it) automatically using JarURLConnection. (Oracle also has a tutorial on using this class.)

    0 讨论(0)
提交回复
热议问题