java動態(tài)添加外部jar包到classpath的實例詳解
java動態(tài)添加外部jar包到classpath的實例詳解
前言:
在項目開發(fā)過程中我們有時候需要動態(tài)的添加外部jar包,但是具體的業(yè)務(wù)需求還沒有遇到過,因為如果動態(tài)添加外部jar包后,我們就需要修改業(yè)務(wù)代碼,而修改代碼就需要重新啟動服務(wù),那樣好像就沒有必要動態(tài)添加外部jar包了,怎么樣才能不重新啟動服務(wù)器就可以使用最新的代碼我沒有找到方法,如果各位知道的話給我點建議,回歸主題,實現(xiàn)動態(tài)添加外部jar包到classpath的方法如下:
String beanClassName = "com.dynamic.DynamicBean3";
Map<String,Class<?>> classMap = new HashMap<String,Class<?>>();
String filePath = "f:\\testDynamicBean-1.0-SNAPSHOT.jar";
String uFilePath = "file:f:\\testDynamicBean-1.0-SNAPSHOT.jar";
URL url1 = new URL(uFilePath);
URLClassLoader urlClassLoader = new URLClassLoader(new URL[] { url1 }, Thread.currentThread()
.getContextClassLoader());
List<JarEntry> jarEntryList = new ArrayList<>();
JarFile jarFile = new JarFile(filePath);
Enumeration<JarEntry> jarEntryEnumeration = jarFile.entries();
while (jarEntryEnumeration.hasMoreElements()){
JarEntry jarEntry = jarEntryEnumeration.nextElement();
if (//jarEntry.getName().startsWith(filePath) &&
jarEntry.getName().endsWith(".class")) {
jarEntryList.add(jarEntry);
}
}
for (JarEntry entry : jarEntryList) {
String className = entry.getName().replace('/', '.');
className = className.substring(0, className.length() - 6);
if(!classMap.containsKey(beanClassName)){
Class<?> loadClass = urlClassLoader.loadClass(className);
classMap.put(className,loadClass);
}
}
try {
Method printMethod = classMap.get(beanClassName).getMethod("printBean3");
printMethod.invoke(classMap.get(beanClassName).newInstance());
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
}
如有疑問請留言或者到本站社區(qū)交流討論,感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
相關(guān)文章
SpringBoot2零基礎(chǔ)到精通之映射與常用注解請求處理
SpringBoot是一種整合Spring技術(shù)棧的方式(或者說是框架),同時也是簡化Spring的一種快速開發(fā)的腳手架,本篇讓我們一起學(xué)習(xí)映射、常用注解和方法參數(shù)的小技巧2022-03-03

