Can't get annotations from classes loaded by custom classloader in tomcat

annotations, classloader, java, tomcat

Solution

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());

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...

Problem

Given the class `org.popper.example.pages.Login` ``` @Page(name="Login") public interface Login { } ``` 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())); } } ``` Running the code as main shows the expected result ``` [@org.popper.fw.annotations.Page(name=Login)] ``` Running the code as servlet in tomcat doesn't find the annotations ``` [] ``` Can anybody tell me why?

Original source