Working with Annotations in Java
205
24-Apr-2025
ICSM Computer
24-Apr-2025Annotations in Java are a form of metadata. They provide data about a program that is not part of the program itself. Annotations have no direct effect on the operation of the code they annotate but are widely used in frameworks (like Spring, JUnit) for configuration and behavior control.
1. Built-in Annotations
Java provides several built-in annotations, such as:
@Override– Ensures that a method is overriding a superclass method.@Deprecated– Marks a method/class as deprecated (shouldn’t be used).@SuppressWarnings– Tells the compiler to ignore specific warnings.2. Creating Custom Annotations
You can define your own annotation using
@interface.Example:
@Retention– Specifies how long the annotation is retained (e.g.,SOURCE,CLASS,RUNTIME).@Target– Indicates where this annotation can be used (e.g.,METHOD,FIELD,TYPE).3. Using Custom Annotation
4. Accessing Annotations with Reflection
You can use reflection to read and process annotations at runtime.
5. Common Framework Use Cases
@Autowired,@Service,@Controller,@RequestMapping.@Test,@BeforeEach,@AfterEach.@Entity,@Table,@Column.Summary Table
@interface@Retention@Target