如何用URLClassLoader来加载一个指定目录下的class类 ServletWeb
程序员文章站
2022-07-15 07:59:46
...
直接插入我的代码:
public class ServletProcessor1 { public void process(Request request, Response response) { // TODO Auto-generated method stub String uri = request.getUri(); System.out.println(uri); String servletName = uri.substring(uri.lastIndexOf("/")+1); URLClassLoader loader = null; try{ URL[] urls = new URL[1]; URLStreamHandler streamHandler = null; File classPath = new File(Constants.WEB_ROOT); String repository = (new URL("file",null,classPath.getCanonicalPath()+File.separator)).toString(); urls[0] = new URL(null,repository,streamHandler); loader = new URLClassLoader(urls); }catch(IOException e){ e.printStackTrace(); } Class myClass = null; try{ myClass = loader.loadClass(servletName); }catch(ClassNotFoundException e){ System.out.println(e.toString()); } Servlet servlet = null; try{ servlet = (Servlet)myClass.newInstance(); servlet.service((ServletRequest)request, (ServletResponse)response); }catch(Exception e){ System.out.println(e.toString()); } } }
运行时,总发现 myClass = loader.loadClass(servletName); 报错,
"servletName" 是有WebRoot/WEb-INF/CLASS文件下是有的,
不过在com/servlet_/test/包下面.
请高手赐教,急呀!
上一篇: Oracle数据库中的Where条件执行顺序是从后往前
下一篇: 初学python遇到的一个小问题