java动态打jar包_java动态加载jar包
目錄結構如下.
├── main
│?? ├── java
│?? │?? └── lu
│?? │?? └── tool
│?? │?? └── jar
│?? │?? ├── InterfaceRunner.java
│?? │?? └── Loader.java
│?? └── resources
└── test
├── java
└── resources
InterfaceRunner.java 為掛載 jar 中類的實現接口
Loader.java 為jar的加載器和執行器
所有第三方包的jar路徑,通過 web 界面管理,然后存儲在一個文件中,這里不實現 web 的管理。
InterfaceRunner.java:package lu.tool.jar;
/**
* Created by xiaozi on 11/29/14.
*/
public interface InterfaceRunner {
public void fire();
}
Loader.javapackage lu.tool.jar;
import java.io.*;
import java.net.URL;
import java.net.URLClassLoader;
/**
* Created by xiaozi on 11/29/14.
*/
public class Loader {
public static void main(String[] args) {
String configFile = System.getProperty("jar.conf");
if (configFile == null || configFile.isEmpty()) {
System.exit(1);
}
System.out.println(configFile);
File file = new File(configFile);
try {
BufferedReader in = new BufferedReader(new FileReader(file));
String s;
while ((s = in.readLine()) != null) {
if (s.isEmpty()) continue;
System.out.println(s);
URL url = new URL(s);
URLClassLoader myClassLoader = new URLClassLoader(new URL[] {url}, Thread.currentThread().getContextClassLoader());
Class> myClass = myClassLoader.loadClass("lu.tool.jar.Runner");
InterfaceRunner action = (InterfaceRunner) myClass.newInstance();
// 達到指定條件的時候觸發,這里僅是個演示
// 在沒有優先級的執行條件下應該使用子進程的方式,防止其中的一個crash掉
action.fire();
myClassLoader.close();
System.out.println("done");
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
jar.conf 存放 jar 的本地的絕對路徑file:///Users/xiaozi/Documents/testrunner/out/artifacts/testrunner_jar/testrunner.jar
被掛載jar包中的類實現package lu.tool.jar;
/**
* Created by xiaozi on 11/29/14.
*/
public class Runner implements InterfaceRunner {
@Override
public void fire() {
System.out.println("Hello, I'm in another jar!");
}
}
總結
以上是生活随笔為你收集整理的java动态打jar包_java动态加载jar包的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 太空舞步是哪首歌啊?
- 下一篇: 周杰伦要结婚了怎么办