您的位置:首页 > 其它

利用URLClassLoader加载两个位置的Class

2015-05-14 22:54 489 查看
内容:分别位于\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");
		}
		
	}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: