动态加载jar

时间:2012-11-22 00:15:28

标签: java jar classloader urlclassloader

在我的java应用程序中,我将一个jar文件(与Maven shade插件一起打包)读入一个字节流。在jar中,有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应用程序中?

更新

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

1 个答案:

答案 0 :(得分:2)

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

代码看起来像:

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

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

您还可以使用JarURLConnection自动检测主类名称(或调用它)。 (Oracle也有a tutorial on using this class。)

相关问题