Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to create a custom annotation with a group of annotations in Java?

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.

like image 639
Lang Avatar asked Sep 03 '18 11:09

Lang


People also ask

How do I create a custom annotation in Java?

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 { }

What is @Test annotation in Java?

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).

How to create custom annotation in Salesforce?

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 :

What is the purpose of a custom class annotation?

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.


1 Answers

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.

like image 59
maaartinus Avatar answered Nov 06 '22 22:11

maaartinus