本文介绍了类级别注释的定义类加载器是否始终是该类的初始类加载器的父级?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设以下内容:

@SomeAnnotation
public interface Foo {
}

我想知道是否总是出现 SomeAnnotation 等于 Foo 的启动类加载器或它的父级。

I would like to know if it is always the case that either the defining classloader of SomeAnnotation is equal to or a parent of the initiating classloader of Foo.

我已阅读。但我不确定这里是否适用。第5.3.4节讨论了加载约束,但是它们似乎不适用于注释。

I have read JVMS v8 section 5.3. but I'm not sure what applies here. Section 5.3.4 talks about loading constraints, but they seem not to apply for annotations.

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

The question I'm asking is because code like this:

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

将在存在不同的类加载器的情况下失败。我知道我可以使用, getAnnotations()必须跳过未知的注释,这意味着可以使用类加载器无法识别的注释。在讨论的真实Java代码的行为验证了该假设。

RetentionPolicy.RUNTIME annotations are available for discovery via the reflection API only. This is done to ensure loose coupling between annotations and annotated code. According to this bug report, getAnnotations() must skip unknown annotations which implies that it's ok to have annotations that are not recognized by the classloader. The behavior of real Java code discussed here validates that assumption.

此行为有两个含义:


  1. 全部无法识别的注释(例如不在类路径中的注释)变为不可见

  2. 为了显示它们,必须由可以访问类型,类型和类型的不同的类加载器完全重载该类。

例如,如果 somepkg.SomeAnnotation someClass 已加载,这将不起作用:

For example if somepkg.SomeAnnotation was not in classpath when someClass was loaded, this will not work:

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

这篇关于类级别注释的定义类加载器是否始终是该类的初始类加载器的父级?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-30 21:10