I have used Lombok in my code to automatically generate getter and setter code. I want to add other personal annotations and use it.
For example, I want to add an @Exist
method which verifies the existence of a key in a list:
@Getter @Setter
public class User {
private String name;
private List<Integer> keys;
public boolean existKeys(Integer key) {
boolean exist = keys.contains(key);
return exist;
}
}
After creating the annotation, I would do something like:
@Getter @Setter
public class User {
private String name;
@Exist
private List<Integer> keys;
}
General Considerations
If you are already using Lombok, you can add custom Lombok transformation annotation and handler.
Define Exists annotation with
@Target(FIELD)
and@Retention(SOURCE)
Create a handler
to process your annotation. Handler class package must start with the
lombok.
prefix. If you need to support Eclipse, etc. in addition to javac, you'll need to write more handlers extending appropriate framework classes.In the handler override/implement the
handle()
method to generate the required code through AST manipulation.You can take as a sample the @Getter implementation:
Annotation: Getter.java
Handler: HandleGetter.java
You can also look into sources of other annotations and handlers to see how to generate particular code.
You'll need to add dependencies on lombok, JDK tools.jar.
Some resources:
The lombok-pg project with a source for a bunch of custom lombok annotations, in particular FluentSetter.java, HandleFluentSetter.java / FluentSetterHandler.java
An overview of a custom transformation
Simple annotation example with explanations.
Note, there are some points to consider here
A more complex alternative without Lombok is to use standard annotation processing for code generation but, AFAIK, you can't change original classes and must generate/use classes that extend them (unless you'll exploit the same back-door as Lombok or resort to a code manipulation like CGLib or ASM).
Lombok Example
Below is some working code to create custom Lombok annotation that I've called @Contains.
It is javac implementation only, no Eclipse, etc. I guess it will be not hard to create a similar handler for Eclipse or other IDE.
It will generate fieldNameContains() member method which is delegated to the fieldName.contains().
Note, the code is just quick and dirty (but working) sample. For production grade annotation, you will need to handle many boundary conditions, check correct types, handle Lombok configuration and so on, as it can be observed in lombok or lombok-pg library sources.
Sample usage
SomeEnity.java
SomeEntityTest.java
Annotation Implementaiton
Contains.java
HandleContains.java