2014-05-08 11:00:03

java 反射运行时加载外部jar到Tomcat StandardClassLoader

加载jar这一部分很容易,可是卸载jar就没那么容易了。加载jar的时候需要用反射去调用URLClassLoader的addURL方法。Tomcat的StandardClassLoader继承于URLClassLoader。
<%@ page language="java" pageEncoding="UTF-8"%>
<%@ page import="java.util.*"%>
<%@page import="java.net.URL"%>
<%@page import="java.lang.reflect.Method"%>
<%@page import="java.net.URLClassLoader"%>
<%
	URLClassLoader c = (URLClassLoader) getClass().getClassLoader().getParent().getParent();
	URL jar = new URL("http://javaweb.org/jars.jar");
	try {
		Method m = URLClassLoader.class.getDeclaredMethod("addURL", URL.class);
		m.setAccessible(true);
		m.invoke(c,new Object[]{jar});
		URL[] url = c.getURLs();
		for(URL u:url){
			out.println(u+"<br/>");
		}
		Class<?> test = Class.forName("com.javaweb.test.Test");
		Method method = test.getDeclaredMethod("test",HttpServletRequest.class);
   		Object obj = method.invoke(test.newInstance(), new Object[]{request});
   		out.println(method.getName()+":"+obj);
	}catch(Exception e){
		e.printStackTrace();
	}
%>
jars.jar内容:
package com.javaweb.test;
import javax.servlet.http.HttpServletRequest;
public class Test{
	public String test(HttpServletRequest request){
		String str = request.getSession().getServletContext().getRealPath("/");
		System.out.println(str);
		return str;
	}
}

输出:

1

发表回复