标签:classloader jdk
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一个接口,这样能动态装载接口的实现类
标签:classloader jdk
原文地址:http://blog.csdn.net/u010278923/article/details/44808389