Java – definition of class level annotation is the class loader always the parent of the class’s startup class loader?

The assumptions are as follows:

@SomeAnnotation
public interface Foo {
}

I want to know whether the definition class loader of someannotation is equal to or the parent of Foo's startup class loader is always like this

I have read JVMs V8 section 5.3 But I don't know if it works here Section 5.3 Section 4 discusses load constraints, but they do not seem to apply to annotations

The question I ask is because of this Code:

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

It will fail in the presence of different class loaders I know I can use getannotations and search the result array for elements with class names equal to someannotation But I want to know if the following can also be:

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

Solution

Short answer: No

A long answer

RetentionPolicy. Runtime annotations can only be found through the reflection API This is done to ensure loose coupling between comments and comment code According to this bug report, getannotations () must skip unknown annotations, which means that annotations cannot be recognized by the classloader The behavior of real java code discussed here confirms this hypothesis

This behavior has two meanings:

>All unrecognized annotations (such as those not in the classpath) become "invisible" > in order to reveal them, the class must be completely reloaded by a different class loader that can access the two types and annotations

For example, if somepkg Someannotation is not in the classpath when loading someclass, which will not work:

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

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

But this will:

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

ClassLoader cl = new urlclassloader(classPathWithSomeClassAndAnnotations,null);
Annotation a = cl.loadClass(someClass.getName()).getAnnotation(cl.loadClass("somepkg.someAnnotation"));
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>