Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 417
overexchange Avatar asked Jun 28 '15 08:06

overexchange


2 Answers

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

like image 148
Nebu Pookins Avatar answered Oct 07 '22 00:10

Nebu Pookins


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
like image 36
Chetan Kinger Avatar answered Oct 07 '22 01:10

Chetan Kinger