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!");

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值