user2426902
user2426902

Reputation:

How to use an annotation to replace code in Java?

I want to be able to process a java project pre-build so I can locate all annotations, such as @Getter, and replace them with an actual getter statement for the assigned field.

@Getter String s = "string";

I basically want to do what "Project Lombok" does, but I want to do it myself, to learn as well as simplify it for my needs.

The problem is, well, I don't know where to start. I have searched and have found nothing of any use, and have tried myself as well, with no luck. I would like it to run on eclipse build, so the jar is automatically correct. I also would like to create it so when I insert the annotation into a java file it doesn't show as an error, which I assume I can fix this with a dependency.

As far as experience goes, I know how to use and create annotations, but only for storing meta-data, and not being used as a placeholder, per-say.

If you have any tips or know of any resources to help me with this, I would greatly appreciate it.

P.S. I already looked through Project Lombok's source code, and it was too extensive to locate what needs to be done.

Upvotes: 2

Views: 1199

Answers (3)

Baldy
Baldy

Reputation: 2002

You'll need to write a custom annotation processor.

Basically you'll be searching for your annotations and adding custom code to the resulting class file before the the final compilation step.

Your processor needs to implement javax.annotation.processing.Processor to handle your annotations. I've done this before for NetBeans and used a good article from a few years ago as a guide http://deors.wordpress.com/2011/10/08/annotation-processors/.

Good luck!

Upvotes: 0

Adarsh Singhal
Adarsh Singhal

Reputation: 362

It's very simple. First of all you need to attach lombok.jar to your project.
Right click your project & go to properties. Attach external jar/library. Now import the following:-

import lombok.Getter;
import lombok.Setter;
import lombok.AccessLevel;
// and so on....

Now you're able to use @Getter @Setter as follows:-

@Getter @Setter private Car car;

Now you're able to use getCar() & setCar(...)
Note:- You may need to enable annotation processing for NetBeans. Don't ask me how to do that. Just google it or visit lombok's site.

Upvotes: -1

Puce
Puce

Reputation: 38132

AFAIK Lombok does some AST manipulation in annotation processors (not 100% sure), which isn't officially supported by the specification. Thus it's more like a hack to overcome some shortcomings in the Java language.

Upvotes: 2

Related Questions