给定班级 org.popper.example.pages.Login
org.popper.example.pages.Login
@Page(name="Login") public interface Login { }
导出到c:\pos\example.jar以下servlet
c:\pos\example.jar
public class PopperServlet extends HttpServlet { private static final long serialVersionUID = 1L; public static void main(String[] args) throws MalformedURLException, ClassNotFoundException { URLClassLoader ucl = new URLClassLoader(new URL[] {new File("c:/pos/example.jar").toURI().toURL()}); System.out.println(Arrays.asList(ucl.loadClass("org.popper.example.pages.Login").getAnnotations())); } public PopperServlet() throws MalformedURLException, ClassNotFoundException { URLClassLoader ucl = new URLClassLoader(new URL[] {new File("c:/pos/example.jar").toURI().toURL()}); System.out.println(Arrays.asList(ucl.loadClass("org.popper.example.pages.Login").getAnnotations())); } }
以main身份运行代码可显示预期结果
[@org.popper.fw.annotations.Page(name=Login)]
在Tomcat中将代码作为servlet运行无法找到注释
[]
谁能告诉我为什么?
和以前一样:关注类加载器层次结构!
new URLClassLoader(new URL[] {new File("c:/pos/example.jar").toURI().toURL()}, PopperServlet.class.getClassloader());
做到了。但是令人惊讶的是,没有找到注解而是a ClassNotFoundException或NoClassDefError,这就是我在加载类时未找到注解的期望值…
ClassNotFoundException
NoClassDefError