I use lombok and JPA in my system. So for the entity classes, all of them looks like:
@Getter
@Setter
@Entity
@NoArgsConstructor
@AllArgsConstructor
public class XxxEntity {
...
}
So my question can I create a custom annotation to grouping these all these annotations?
so it may look like:
@CustomAnnotation
public class XxxEntity {
...
}
And when I use the @CustomAnnotation, it will apply all the above annotation to that class.
Is this possible?
Thanks.
The first step toward creating a custom annotation is to declare it using the @interface keyword:. public @interface JsonSerializable { } The next step is to add meta-annotations to specify the scope and the target of our custom annotation: @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.Type) public @interface JsonSerializable { }
P.S This unit test example is inspired by this official Java annotation article. 1. @Test Annotation This @interface tells Java this is a custom annotation. Later, you can annotate it on method level like this @Test (enable=false).
The first step to creating a custom annotation is to declare it using the @interface keyword : The next step is to specify the scope and the target of our custom annotation : 2. Field Level Annotation Using the same fashion, we create our second annotation to mark the fields that we are going to include in the generated JSON :
Since it has no methods, it serves as a simple marker to mark the classes we need. One thing to note here is that any class-level custom annotation cannot have any parameters and must not throw any exception.
No, it's not possible. You can lump your annotations together using a new annotation, but the annotation processor won't understand it. The @Caching
annotation from Spring is just an example of an annotation known by the annotation processor. If you create an own annotation by copying @Caching
, I'd bet you'll see that it does not work.
In theory, it could work as an annotation processor can read any annotation and look inside. However, it's totally unclear how an unknown annotation should be processed. Putting other annotations inside has no standardized meaning.
Especially, this does not work for Lombok. There are a few issues requesting this, e.g., here, but it's pretty complicated.
The ultimate solution would be an annotation pre-processor understanding compound annotations and replacing them by their constituents before ordinary annotation processors run. But there's no such thing and AFAIK no plans for it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With