假设如下:
@SomeAnnotation
public interface Foo {
}
Run Code Online (Sandbox Code Playgroud)
我想知道是否始终如此定义的类加载器SomeAnnotation等于或者是启动类加载器的父类Foo.
我已阅读JVMS v8第5.3节.但我不确定这里适用的是什么.第5.3.4节讨论了加载约束,但它们似乎不适用于注释.
我问的问题是因为这样的代码:
Class<?> fooClass = //will in some way obtain a reference to class Foo
fooClass.getAnnotation(SomeAnnotation.class);
Run Code Online (Sandbox Code Playgroud)
在不同的类加载器存在的情况下会失败.我知道我可以使用getAnnotations并在结果数组中搜索类名等于的名称的元素SomeAnnotation.但我想知道以下是否也会有效:
Class<?> fooClass = //will in some way obtain a reference to class Foo
fooClass.getAnnotation((Class<? extends Annotation>) fooClass
.getClassLoader().loadClass(SomeAnnotation.class.getName()));
Run Code Online (Sandbox Code Playgroud) 给定班级 org.popper.example.pages.Login
@Page(name="Login")
public interface Login {
}
Run Code Online (Sandbox Code Playgroud)
导出到c:\pos\example.jar以下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()));
}
}
Run Code Online (Sandbox Code Playgroud)
以main身份运行代码可显示预期结果
[@org.popper.fw.annotations.Page(name=Login)]
Run Code Online (Sandbox Code Playgroud)
在Tomcat中将代码作为servlet运行无法找到注释
[]
Run Code Online (Sandbox Code Playgroud)
谁能告诉我为什么?