当我使用URLClassLoader加载类时,以下代码是正确的
Class c1 = classLoader.loadClass("jjzhu.study.tomcat.servlet.PrimitiveServlet");
for(Method m: c1.getDeclaredMethods()){
System.out.println(m.getName());
}
但是当我这样做时,它会抛出ClassNotFoundException
Class c = classLoader.loadClass(String.format("jjzhu.study.tomcat.servlet.%s",servletName));
为什么呢? 完整的功能代码是:
public void process(Request request, Response response) throws ServletException, IOException {
String uri = request.getUri();
String servletName = uri.substring(uri.lastIndexOf("/") + 1);
String path = ServletProcessor1.class.getResource("/").toString();
URL classUrl;
URLClassLoader classLoader = null;
try {
classUrl = new URL(path+"jjzhu/study/tomcat/servlet");
System.out.println(path+"jjzhu/study/tomcat/servlet");
URL[] classUrls = {classUrl};
classLoader = new URLClassLoader(classUrls);
// this is ok!
Class c1 = classLoader.loadClass("jjzhu.study.tomcat.servlet.PrimitiveServlet");
for(Method m: c1.getDeclaredMethods()){
System.out.println(m.getName());
}
// but this failed
Class c = classLoader.loadClass(String.format("jjzhu.study.tomcat.servlet.%s",servletName));
for(Method m: c.getDeclaredMethods()){
System.out.println(m.getName());
}
Servlet servlet = (Servlet)c.newInstance();
servlet.service(request, response);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
}
}
例外:
init
destroy
service
getServletConfig
getServletInfo
java.lang.ClassNotFoundException: jjzhu.study.tomcat.servlet.PrimitiveServlet
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
at jjzhu.study.tomcat.ex02.pyrmont.ServletProcessor1.process(ServletProcessor1.java:39)
at jjzhu.study.tomcat.ex02.pyrmont.HttpServer1.await(HttpServer1.java:41)
at jjzhu.study.tomcat.ex02.pyrmont.HttpServer1.main(HttpServer1.java:60)