Are Java annotations an addition to notation or functionality?

Are Java annotations to add functionality to the Java code, and not just add documentation about what is happening in the code? What is the most advanced / sophisticated functionality you could add to your code through annotation?

+4
source share
4 answers

Annotations are basically no more than a tag (with additional additional data) in a class / method / field. Other code (libraries or tools) can detect these tags and perform functions that depend on the annotations found. I do not see a real restriction on the complexity of functionality, possibly added by annotations. This can, for example, emulate AOP (adding functionality before or after a method with annotation).

+2
source

Annotations per se add only information (metadata) to the class.

However, you can easily create a system that uses this metadata to provide additional functionality.

For example, you can use apt to generate classes based on the information provided by the annotation.

+2
source

An annotation needs a tool to respond to it. If such a tool does not exist, the annotation is simply a designation. A β€œtool” can be an APT based agent or some piece of code that uses reflection (for example, JUnit @Test ).

Several annotations are recognized by the Java compiler and therefore have predefined semantics: @Override , @Deprecated , @Target .

+2
source

I would understand Annotations as a way to document your code in a machine-readable way. For example, in Hibernate you can specify all the information about saving your objects as annotations. This is available to you, not the remote XML file. But also readable for a tool for creating configurations, database schemas, etc.

+1
source

Source: https://habr.com/ru/post/1305738/


All Articles