Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create custom Annotation as alias for Framework-Annotation?

is it possible to create a custom Alias-Annotation to be used instead of

@SuppressWarnings("unused") // EventBus
public void onEvent(SomeMessage msg) { ... }

like

@EventBusListener
public void onEvent(SomeMessage msg) { ... }

This would be more self-documenting and should include the SuppressWarnings of course... Sorry if this trivial but my googling failed me so far.

like image 436
hotzen Avatar asked Jun 12 '15 23:06

hotzen


People also ask

How do we create customized annotations in spring?

Custom annotations can be created in spring framework using Java Aspect Oriented programming and Java Reflection API.

Can we create custom annotation in spring boot?

In this way, we can create different custom annotations for validation purposes. You can find the full source code here. It is easy to create and use custom annotations in Java. Java developers will be relieved of redundant code by using custom annotations.


1 Answers

One approach is to write an annotation processor that transforms the AST (the compiler's internal representation of the source code). At each occurrence of @EventBusListener, your annotation processor would insert an occurrence of @SuppressWarnings("unused"). Later phases of the compiler would see the annotation.

Annotation processors do not ordinarily change the source code, so this takes a bit of work. The AST is supplied to the annotation processor as an interface type, so your annotation processor would need to cast this to a concrete class and perform side effects on the concrete class. Project Lombok is an example of annotation processing that modifies the AST during compilation.

You might just want to write the @SuppressWarnings("unused") annotation, though.

like image 53
mernst Avatar answered Oct 19 '22 23:10

mernst