自訂classloader裝載fastjson包,fastjson自訂註解
public class Test {/** * @param args * @throws IllegalAccessException * @throws InstantiationException */public static void main(String[] args) throws InstantiationException, IllegalAccessException {ClassLoaderUtil.loadJarFile(new File("D:\\MyEclipse10\\unicomspace\\testclassload\\fastjson-1.1.26.jar"));Class<?> clazz = ClassLoaderUtil.loadclass("com.alibaba.fastjson.JSON");System.out.println(clazz.getSimpleName());}}
上面的代碼是測試,下面是實現
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; /** 15. * @author obullxl 16. * 17. * email: obullxl@163.com MSN: obullxl@hotmail.com QQ: 303630027 18. * 19. * Blog: http://obullxl.iteye.com 20. */ public final class ClassLoaderUtil { /** 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(); } } public static final Class<?> loadclass(String handler) { try { Class<?> clazz = system.loadClass(handler); return clazz; } catch (Exception e) { e.printStackTrace(); }return null; } /** * <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); } } }
在很多情況是newinstance一個介面,這樣能動態裝載介面的實作類別