How do you implement a "Preprocessor" Annotation?

Asked

Viewed 105 times

2

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

POJO with getters and traditional 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 @Setter Annotations make Lombok generate the getters and setters methods for you, so if you invoke them in other classes, they do not give compilation error.

But it’s strange: The tutorials and lessons of Annotations I saw only taught how to use Annotations to insert information.

How I create code-generating Annotations, create compilation rules and things like?

  • 1

    If you want to do something like Lombok faz, see how it’s done in the original

  • But that’s where it is: The file of the Annotation is just an Annotation. What magic happens for this Annotation to generate code?

  • what do you want with this question? Understand how it works or create your own annotation?

1 answer

2


Browser other questions tagged

You are not signed in. Login or sign up in order to post.