How do I implement a preprocessor annotation?

2

I've learned that Annotations in Java are just a way to inject metadata into code. However, I have seen that frameworks and some libraries have annotations that "magically" generate code or define compilation rules. One example is projectlombok:

POJO with traditional getters and setters:

public class DataExample {
    private int data;

    public DataExample(int data) {
        this.data = data;
    }

    public void setData(int data) {
        this.data = data;
    }

    public int getData() {
        return data;
    }
}

POJO using Lombok:

public class DataExample {
    @Getter @Setter private int data;

    public DataExample(int data) {
        this.data = data;
    }
}

The difference is that the @Getter and @etter annotations cause Lombok to generate the getters and setters methods for you, so if you invoke them in other classes, they do not give a compile error.

But it's strange: The tutorials and lessons of annotations I saw only taught you to use annotations to enter information.

How do I create annotations that generate code, create compilation rules, and the like?

    
asked by anonymous 27.08.2014 / 23:28

1 answer

2

What happens is that Lombok uses a mechanism known as APT (Annotation Processing Tool). With this it is possible that the getters and setters are still generated at compile time. An interesting link about this:

link

    
29.08.2014 / 13:06