最近的系统需要添加一个新的功能,就是在不重启服务的情况下,动态加载用户上传的jar包,先来过一遍简单的jar包的动态加载。
-
方法一:通过配置文件读取jar包位置
-
方法二:把jar的位置放置于固定的位置
首先来看一下大致文件结构:
第一步,定义一个接口:
public interface InterfaceAction {
String action();
}
第二步,写测试这个接口的实现类
public class TestAction implements InterfaceAction {
public String action() {
System.out.println("TestAction");
retrun "action()";
}
}
第三步,把TestCL2编译打包成jar包,然后丢到F:/jar/下
第四步,写测试类来测试结果
public class TestMain {
public static void main(String[] args) {
try {
//第一种 配置成文件格式
File file = new File("F:\\jar\\test.txt");
BufferedReader in = new BufferedReader(new FileReader(file));
String s = new String();
while ((s = in.readLine()) != null) {
System.out.println(s);
URL url = new URL(s);
URLClassLoader myClassLoader = new URLClassLoader(new URL[] { url }, Thread.currentThread().getContextClassLoader());
Class<? extends InterfaceAction> myClass = (Class<? extends InterfaceAction>) myClassLoader.loadClass("com.java.jarloader.TestAction");
InterfaceAction action = (InterfaceAction) myClass.newInstance();
String str = action.action();
System.out.println(str);
//第二种
URL url1 = new URL("file:F:\\jar\\TestCL2.jar");
URLClassLoader myClassLoader1 = new URLClassLoader(new URL[] { url1 }, Thread.currentThread().getContextClassLoader());
Class<?> myClass1 = myClassLoader1.loadClass("com.java.jarloader.TestAction");
InterfaceAction action1 = (InterfaceAction) myClass1.newInstance();
String str1 = action1.action();
System.out.println(str1);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
第五步,结果验证。