Suppose the following:
@SomeAnnotation
public interface 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
.
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);
will fail in the presence of different classloaders. I know I could use getAnnotations and search in the resulting array for an element whose class name is equal to the name of SomeAnnotation
. But I'm wondering if the following will work too:
Class<?> fooClass = //will in some way obtain a reference to class Foo
fooClass.getAnnotation((Class<? extends Annotation>) fooClass
.getClassLoader().loadClass(SomeAnnotation.class.getName()));
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…