package com.biao.util;
import java.io.File;
import java.net.URL;
import java.net.URLClassLoader;
import com.biao.ActionInterface;
/**
* 使用URLClassLoader动态的加载Class类和jar包中的类. 这样,可以把这些类路径放在配置文件中,动态的加载.
*/
public class ClassLoaderUtil extends URLClassLoader {
private static ClassLoaderUtil instance = new ClassLoaderUtil();
public ClassLoaderUtil() {
super(new URL[0]);
}
public static ClassLoaderUtil getInstance() {
return instance;
}
/**
* 加载类,如果找不到这个类,则返回null.
*
* @param path 类所有目录或者所在jar文件的路径.
* @param className 要加载的类的名字
* @return 返回类的实例。如果找不到这个类,则返回null.
*/
public Object loadClass(String path, String className) {
Object obj = null;
try {
URL url = new File(path).toURI().toURL();
addURL(url); // 同一个目录只会保存一个url
Class clazz = loadClass(className); // 加载类
obj = clazz.newInstance();
} catch (Exception e) {
e.printStackTrace();
}
return obj;
}
public static void main(String[] args) {
// 传入jar包路径或者Class所在目录(不包括包名)
// 加载包中的类
ActionInterface ai = (ActionInterface) ClassLoaderUtil.getInstance().loadClass(
"plugins/ai_test.jar", "com.biao.MyAction");
System.out.println(ai.action());
// 加载某目录下的类
ai = (ActionInterface) ClassLoaderUtil.getInstance().loadClass(
"/Users/Biao/Documents/Workspace/NewWork/JT2/bin/", "com.biao.MyAction2");
System.out.println(ai.action());
ai = (ActionInterface) ClassLoaderUtil.getInstance().loadClass(
"/Users/Biao/Documents/Workspace/NewWork/JT2/bin", "com.biao.MyAction2");
System.out.println(ai.action());
URL[] urls = ClassLoaderUtil.getInstance().getURLs();
for (URL url : urls) {
System.out.println(url.getFile());
}
}
}