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

Niuhuru Lang :

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.

maaartinus :

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.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=68648&siteId=1