日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > java >内容正文

java

Java运行时动态加载类之ClassLoader加载class及其依赖jar包

發布時間:2025/4/16 java 37 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Java运行时动态加载类之ClassLoader加载class及其依赖jar包 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

需求場景是:通過ClassLoader動態加載外部class文件,class文件又依賴某個具體jar包,需要動態加載jar包,采用URLClassLoader。

1、xml配置文件

<?xml version="1.0" encoding="ISO-8859-1"?> <classes><class name="User"> <jar>ETLEnc.jar</jar><method>say</method> </class> </classes>
放在D:\\tmp\\目錄下;

2、User.class文件放在D:\\tmp\\目錄下,依賴ETLEnc.jar也放在D:\\tmp\\目錄下,User代碼如下:

package cn.fjs;import com.gddx.enc.ETLEncode;public class User {public void say(String name){ETLEncode ete=new ETLEncode();try {System.out.println(ete.encrypt(name));} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();} } }
其中com.gddx.enc.ETLEncode是ETLEnc.jar包中的類。

3、xml文件解析類代碼:

package cn.fjs;import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map;import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException;import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException;//解析xml文件,獲取類和方法 public class DynamicDom {private static DocumentBuilderFactory dbFactory = null; private static DocumentBuilder db = null; private static Document document = null; static{ try { dbFactory = DocumentBuilderFactory.newInstance(); db = dbFactory.newDocumentBuilder(); } catch (ParserConfigurationException e) { e.printStackTrace(); } } public Map<String,List<String>> getMethods(String fileName) throws SAXException, IOException{ Map<String,List<String>> classes = new HashMap<String, List<String>>();document = db.parse(fileName); NodeList nList = document.getElementsByTagName("class");for(int i = 0 ; i<nList.getLength();i++){ Node node = nList.item(i); Element ele = (Element)node; if(node.getNodeType() == Element.ELEMENT_NODE){String clazz = ele.getAttribute("name"); List<String> methods = new ArrayList<String>();String method = ele.getElementsByTagName("method").item(0).getTextContent();methods.add(method);classes.put(clazz, methods); }}return classes;} public Map<String,List<String>> getJars(String fileName) throws SAXException, IOException{ Map<String,List<String>> classes = new HashMap<String, List<String>>();document = db.parse(fileName); NodeList nList = document.getElementsByTagName("class");for(int i = 0 ; i<nList.getLength();i++){ Node node = nList.item(i); Element ele = (Element)node; if(node.getNodeType() == Element.ELEMENT_NODE){String clazz = ele.getAttribute("name"); List<String> jars = new ArrayList<String>();String jar = ele.getElementsByTagName("jar").item(0).getTextContent();jars.add(jar);classes.put(clazz, jars); }}return classes;} }
4、動態加載jar包工具類:

package cn.fjs;import java.io.File; import java.lang.reflect.Method; import java.net.URL; import java.net.URLClassLoader; import java.util.ArrayList; import java.util.List;public final class JarLoaderUtil {/** URLClassLoader的addURL方法 */ private static Method addURL = initAddMethod(); /** 初始化方法 */ private static final Method initAddMethod() { try { Method add = URLClassLoader.class .getDeclaredMethod("addURL", new Class[] { URL.class }); add.setAccessible(true); return add; } catch (Exception e) { e.printStackTrace(); } return null; } private static URLClassLoader system = (URLClassLoader) ClassLoader.getSystemClassLoader(); /** * 循環遍歷目錄,找出所有的JAR包 */ private static final void loopFiles(File file, List<File> files) { if (file.isDirectory()) { File[] tmps = file.listFiles(); for (File tmp : tmps) { loopFiles(tmp, files); } } else { if (file.getAbsolutePath().endsWith(".jar") || file.getAbsolutePath().endsWith(".zip")) { files.add(file); } } } /** * <pre> * 加載JAR文件 * </pre> * * @param file */ public static final void loadJarFile(File file) { try { addURL.invoke(system, new Object[] { file.toURI().toURL() }); //System.out.println("加載JAR包:" + file.getAbsolutePath()); } catch (Exception e) { e.printStackTrace(); } } /** * <pre> * 從一個目錄加載所有JAR文件 * </pre> * * @param path */ public static final void loadJarPath(String path) { List<File> files = new ArrayList<File>(); File lib = new File(path); loopFiles(lib, files); for (File file : files) { loadJarFile(file); } } }

參考:http://blog.csdn.net/fjssharpsword/article/details/64905874

URLClassLoader也可以動態加載jar包的類并執行具體方法。


5、測試類:

package cn.fjs;import java.io.File; import java.net.URL; import java.net.URLClassLoader; import java.util.List; import java.util.Map; import cn.fjs.DynamicClassLoader; import cn.fjs.DynamicDom;public class DynamicClassLoaderTest {public static String FilePath="D:\\tmp\\";public static void main(String[] args) {DynamicDom dmo = new DynamicDom();//xml文件解析類Map<String, List<String>> classes;Map<String, List<String>> jars;try {//動態記載依賴包jars = dmo.getJars(FilePath+"a.xml");for(String key:jars.keySet()){for(String jar : jars.get(key)){JarLoaderUtil.loadJarFile(new File(FilePath+jar));}} //動態加載類DynamicClassLoader loader = new DynamicClassLoader(new String[]{FilePath});classes = dmo.getMethods(FilePath+"a.xml");for(String key:classes.keySet()){ for(String clazz : classes.get(key)){ Class<?> c =loader.findClass(key);//類名字//c.getMethod(clazz).invoke(c.newInstance());//方法名字c.getMethod(clazz,String.class).invoke(c.newInstance(),"fjs");//帶參數}} }catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}} }


總結

以上是生活随笔為你收集整理的Java运行时动态加载类之ClassLoader加载class及其依赖jar包的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。