利用URLClassLoader加载两个位置的Class

这篇博客介绍了如何使用URLClassLoader在Java中加载位于不同位置的类,包括myAppWEB-INFclasses和webroot下的类。通过创建URL数组来指定多个类路径仓库。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值