History of the issue:
Annotations appeared in Java 5 to add metadata to the bytecode without changing the actual logic of the program. Annotations allow for easily supplying classes and methods with additional information for frameworks, compilers, or parsers.
Problem:
Poorly designed or improperly used annotations lead to complications in code maintenance. Sometimes developers confuse the applicability of annotations or do not understand how to create their own, and are unaware of the possibility to create annotations with parameters.
Solution:
Creating a custom annotation:
import java.lang.annotation.*; @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface MyTest { String value() default ""; }
Using the annotation:
public class TestClass { @MyTest("Example") public void testMethod() {...} }
Key features:
Can an annotation inherit from another annotation?
Answer: No, annotations in Java do not support inheritance from one another.
Is it possible to make the annotation’s work mandatory in all subclasses of a class?
Answer: Not directly. You need to additionally check for the presence of the annotation via reflection, manually implementing similar control.
What is the difference between @Retention(CLASS) and @Retention(RUNTIME)?
Answer:
In a project, they decided to replace XML configuration with annotations, but didn’t add @Retention(RUNTIME)
Pros:
Cons:
Configured a custom annotation @Audit on methods, controlling the audit of business operations, with reflection of the actual logic call on the server.
Pros:
Cons: