本文介绍了无法从tomcat中自定义类加载器加载的类中获取注释的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
给定类 org.popper.example.pages.Login
@Page(name="Login")
public interface Login {
}
导出到c:\pos\example.jar
和下面的servlet
exported to c:\pos\example.jar
and the following servlet
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 方式运行代码显示预期结果
Running the code as main shows the expected result
[@org.popper.fw.annotations.Page(name=Login)]
在tomcat中以servlet的形式运行代码没有找到注解
Running the code as servlet in tomcat doesn't find the annotations
[]
谁能告诉我为什么?
推荐答案
和往常一样:注意类加载器层次结构!
It's the same as always: Regard the classloader-hierarchy!
new URLClassLoader(new URL[] {new File("c:/pos/example.jar").toURI().toURL()}, PopperServlet.class.getClassloader());
成功了.但令人惊讶的是,没有找到注释而是 ClassNotFoundException
或 NoClassDefError
,这就是我在加载类时找不到注释时的预期......
did the trick. But it's surprising that annotations aren't found instead a ClassNotFoundException
or NoClassDefError
, thats what I expected when annotations are not found when loading a class...
这篇关于无法从tomcat中自定义类加载器加载的类中获取注释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!