Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to hook custom compiler logic based on annotations

I want to define a few annotations that will allow extra warnings/errors to be reported during compilation (similar in concept to the @Nullable and @NotNull annotations in IntelliJ).

I would like to be able to write some compiler hooks that will also add my compilation logic based on those attributes.

I want a generic hook if possible, however since we are using Eclipse - it would also be a benefit if we had that ability.

I'd like to know:

  1. Is it possible? (any of the options above)
  2. Where do I start?
  3. I had little experience with annotations so far, so if I'm going about this the wrong way - I'd like to know that and if possible get a better direction to go with.

Thanks.

like image 637
RonK Avatar asked Jun 19 '10 20:06

RonK


People also ask

What is @interface annotation in Java?

Annotation is defined like a ordinary Java interface, but with an '@' preceding the interface keyword (i.e., @interface ). You can declare methods inside an annotation definition (just like declaring abstract method inside an interface). These methods are called elements instead.

How does annotation processing work?

The annotation processing is done in multiple rounds. Each round starts with the compiler searching for the annotations in the source files and choosing the annotation processors suited for these annotations. Each annotation processor, in turn, is called on the corresponding sources.

How does Lombok annotation work?

Lombok acts as an annotation processor that “adds” code to your classes at compile time. Annotation processing is a feature added to the Java compiler at version 5. The idea is that users can put annotation processors (written by oneself, or via third-party dependencies, like Lombok) into the build classpath.

Are annotations necessary in Java?

Annotations are used to provide supplemental information about a program. Annotations start with '@'. Annotations do not change the action of a compiled program. Annotations help to associate metadata (information) to the program elements i.e. instance variables, constructors, methods, classes, etc.


1 Answers

You can use the Java Annotation Processor (see JSR 269: Pluggable Annotation Processing API) for that. From Annotation checking at compile time with Java Annotation Processor:

The JSR 269 states that you can implement a plug-in for the compiler which can handle the annotations. This plug-in can be given as parameter at compile time, so your code will be called when one of your annotation appears in source code.

The mentioned link provides an example that will get you started.

See also:

  • Annotation Processing Tool (apt)
like image 112
Pascal Thivent Avatar answered Oct 28 '22 15:10

Pascal Thivent