Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 608
mibutec Avatar asked Mar 21 '23 09:03

mibutec


1 Answers

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

like image 51
mibutec Avatar answered Mar 26 '23 21:03

mibutec