利用URLClassLoader加载两个位置的Class

内容:分别位于\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");
		}
		
	}
}


郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。