简体   繁体   中英

How to implement something similar to the @Override java annotation?

With this jdk code in ../java/lang/Override.java ,

package java.lang;
import java.lang.annotation.*;
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.SOURCE)

public @interface Override {
}

having just annotation declaration, java compiler is intelligent enough to detect error(compile time):

The method toString123() of type Example must override or implement a supertype method

in the below problem code.

package annotationtype;

public class Example {

    @Override public String toString() {
       return "Override the toString() of the superclass";
    }

    @Override public String toString123() {
       return "Override the toString123() of the superclass";
    }

    public static void main(String[] args) {

    }


}

Annotation declaration for Override just gets compiled to,

interface java.lang.Override extends java.lang.annotation.Annotation{
}

which is nothing more than an interface .

So,

How does interface java.lang.Override syntax help java compiler to detect above error at compile time?

The implementation that triggers the compile error doesn't lie in the annotation, it lies in the Java compiler.

If you want to write your own similar annotation processor, you would use the annotation processor API: http://docs.oracle.com/javase/7/docs/api/javax/annotation/processing/Processor.html

which is nothing more than an interface.

So,

How does interface java.lang.Override syntax help java compiler to detect above error at compile time?

That's right. Override is nothing more than an interface. The actual work is done by the java compiler. How the compiler does this is not specified.

Here are some links that explain how to work with an AnnotationProcessor to implement something similar to @Override :

  1. Processor Java doc
  2. Java annotation processing tool
  3. Code generation using AnnotationProcessor
  4. Annotation Processor, generating a compiler error
  5. Source code analysis using Java 6 API
  6. Playing with Java annotation processing

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM