Java – how is it possible to use @ retention annotation recursively?

In the source code of @ retention annotation in Java, @ retention is used in its definition, which is possible

Even retentionpolicy is set to runtime, so how to execute it before it is ready to run

package java.lang.annotation;

@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface Retention {
    /**
     * Returns the retention policy.
     * @return the retention policy
     */
    RetentionPolicy value();
}

Solution

This is not true recursion It is just a forward reference to the respective interfaces of the classes after "later" Java allows the use of forward references There are various restrictions on this (see the Java language specification, for example, section 8.3.2.2) – but none of these restrictions apply here

In addition: remember, there are no special compilation steps here The compiler just creates a common class file for the retention interface But then: the compiler probably has hard coding knowledge about this interface If using retentionpolicy Source, the compiler will exclude comments from the compiled class file This means that the compiler must perform some kind of check (to determine whether something is annotated and the source policy is enabled)

In other words: the compiler may contain something similar

if (x instaceof Retention) ...

And this code exists in the compiler The above works normally when compiling other comments, but it also works normally when compiling the retention interface itself

But the key message is: no recursion, just forward reference Define what to use later

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
分享
二维码
< <上一篇
下一篇>>