gpt4 book ai didi

java - 类级别注释的定义类加载器是否始终是该类的启动类加载器的父级?

转载 作者:搜寻专家 更新时间:2023-10-30 21:30:31 24 4
gpt4 key购买 nike

假设如下:

@SomeAnnotation
public interface Foo {
}

我想知道 SomeAnnotation 的定义类加载器是否总是这样等于或为 Foo 的初始类加载器的父级.

我已阅读 JVMS v8 section 5.3 .但我不确定这里适用什么。 5.3.4节讲了loading constraints,但是好像没有申请注解。

我问的问题是因为这样的代码:

    Class<?> fooClass = //will in some way obtain a reference to class Foo
fooClass.getAnnotation(SomeAnnotation.class);

将在存在不同类加载器时失败。我知道我可以使用 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()));

最佳答案

简短的回答:没有

长答案。

RetentionPolicy.RUNTIME 注释仅可通过反射 API 进行发现。这样做是为了确保注释和注释代码之间的松散耦合。根据this bug report , getAnnotations() 必须跳过未知注释,这意味着可以使用类加载器无法识别的注释。讨论了真实 Java 代码的行为 here验证了该假设。

这种行为有两个含义:

  1. 所有无法识别的注释(例如不在类路径中的注释)都变得“不可见”
  2. 为了显示它们,类必须由可以访问类型和注释的不同类加载器完全重新加载。

例如,如果加载 someClasssomepkg.SomeAnnotation 不在类路径中,这将不起作用:

Class<?> someClass = ....
URL [] classPathWithAnnotations = ....

ClassLoader cl = new URLClassLoader(classPathWithAnnotations);
Annotation a = someClass.getAnnotation(cl.loadClass("somepkg.SomeAnnotation"));
// a will be null

但这会:

Class<?> someClass = ....
URL [] classPathWithSomeClassAndAnnotations = ....

ClassLoader cl = new URLClassLoader(classPathWithSomeClassAndAnnotations, null);
Annotation a = cl.loadClass(someClass.getName()).getAnnotation(cl.loadClass("somepkg.SomeAnnotation"));

关于java - 类级别注释的定义类加载器是否始终是该类的启动类加载器的父级?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23437443/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com