内容:分别位于\myApp\WEB-INF\classes下的类和\webroot下的类,利用URL数组指定多个仓库位置加载。
MyClassLoader:
public class MyClassLoader {
public static final String WEB_ROOT = System.getProperty("user.dir") +
File.separator + "webroot";
public static final String WEB_APP = System.getProperty("user.dir") +
File.separator + "myApp" + File.separator + "WEB-INF"
+ File.separator + "classes";
public static void main(String[] args) {
URLClassLoader loader = null;
try {
URL[] urls = new URL[2];
URLStreamHandler streamHandler = null;
File classPath = new File(WEB_ROOT);
File appPath = new File(WEB_APP);
String repository1 = (new URL("file", null, classPath.getCanonicalPath() + File.separator)).toString() ;
String repository2 = (new URL("file", null, appPath.getCanonicalPath() + File.separator)).toString() ;
urls[0] = new URL(null, repository1, streamHandler);
urls[1] = new URL(null, repository2, streamHandler);
loader = new URLClassLoader(urls);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Class myClass = null;
Class appClass = null;
try {
myClass = loader.loadClass("ModernServlet");
appClass = loader.loadClass("PrimitiveServlet");
} catch (Exception e) {
System.out.println("error");
}
Servlet servlet = null;
try {
servlet = (Servlet) myClass.newInstance();
servlet.init(null);
servlet = (Servlet) appClass.newInstance();
servlet.init(null);
} catch (Exception e) {
System.out.println("error");
}
}
}