Author
Java Annotations are widely used to make code clean, configurable, and dynamic.
They provide additional information to the compiler and runtime without changing the actual program logic.
Annotations are especially useful in frameworks and real-world applications, where they help reduce boilerplate code and simplify development.
? In modern Java development, annotations play a key role in building scalable, maintainable, and well-structured applications.
Annotations are used to validate data automatically without writing manual checks.
Example (Spring / Hibernate Validation)
import jakarta.validation.constraints.*;
class User {
@NotNull
private String name;
@Size(min = 3, max = 20)
private String username;
public User(String name, String username) {
this.name = name;
this.username = username;
}
}
@NotNull → Ensures the field is not null@Size(min = 3, max = 20) → Validates the length of the stringKey Points
Annotations are used to configure applications instead of using XML files.
Example (Spring Dependency Injection)
import org.springframework.stereotype.Component;
import org.springframework.beans.factory.annotation.Autowired;
@Component
class UserService {
public void print() {
System.out.println("User Service Working");
}
}
@Component
class UserController {
@Autowired
UserService service;
public void execute() {
service.print();
}
}
@Component → Tells Spring to manage the class as a bean@Autowired → Automatically injects the required dependencyKey Points
Annotations can be read and processed at runtime using Reflection.
Example (Custom Annotation + Reflection)
import java.lang.annotation.*;
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnotation {}
@MyAnnotation
class Test {}
public class Main {
public static void main(String[] args) {
if (Test.class.isAnnotationPresent(MyAnnotation.class)) {
System.out.println("Annotation found");
} else {
System.out.println("Annotation not found");
}
}
}
@Retention(RetentionPolicy.RUNTIME) → Makes the annotation available at runtime.isAnnotationPresent() → Checks whether the annotation exists on the class.Key Points
Annotations are mainly used for improving how Java applications are written and managed.
? These use cases make Java applications cleaner, smarter, and more maintainable, especially in modern frameworks and large-scale systems.