动态加载jar [英] Load jar dynamically

查看:112
本文介绍了动态加载jar的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的java应用程序中,我将一个jar文件(与Maven shade插件一起打包)读入一个字节流。在jar中有一个入口点类,在 POM.xml中定义

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>

如何动态地将这样的类加载到我的Java应用程序中?

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

更新:


  • jar作为字节流加载,不会驻留在文件系统或URL

推荐答案

最简单的方法是使用 URLClassLoader 而不是尝试从字节流中从头开始。您始终可以将.jar写入临时文件并创建一个URL。

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.

代码如下所示:

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

loader.loadClass("com.mycompany.TheEntryPoint");

您还可以使用 JarURLConnection 。 (Oracle还有使用此课程的教程。)

这篇关于动态加载jar的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆