Load jar dynamically

ε祈祈猫儿з 提交于 2020-01-11 12:56:10

问题


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

<build>
  ...
  <plugins>
    ...
    <plugin>
      <groupId>org.apache.maven.plugins</groupId>
      <artifactId>maven-jar-plugin</artifactId>
      <configuration>
        <archive>
          <manifest>
            <mainClass>com.mycompany.TheEntryPoint</mainClass>
          </manifest>
        </archive>
      </configuration>
    </plugin>
  </plugins>
</build>

How do I load such class into my java app dynamically?

Update:

  • The jar is loaded as byte stream and does not reside in the file system or URL

回答1:


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



来源:https://stackoverflow.com/questions/13504120/load-jar-dynamically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!