码迷,mamicode.com
首页 > Web开发 > 详细

利用URLClassLoader加载两个位置的Class

时间:2015-05-14 23:53:25      阅读:181      评论:0      收藏:0      [点我收藏+]

标签:

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


利用URLClassLoader加载两个位置的Class

标签:

原文地址:http://blog.csdn.net/u011345136/article/details/45727715

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!