# Java Annotations Explained

Java annotations provide metadata about your code without affecting its execution. Here’s a basic example:

@Override
public String toString() {
return "Custom toString implementation";
}
@Deprecated
public void oldMethod() {
System.out.println("This method is deprecated");
}

You can create custom annotations for various purposes:

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface LogExecutionTime {
String value() default "";
}
public class Example {
@LogExecutionTime("Processing data")
public void processData() {
// Method implementation
System.out.println("Processing...");
}
}

Annotations are widely used in frameworks like Spring and Hibernate for configuration and behavior modification:

@RestController
@RequestMapping("/api")
public class UserController {
@GetMapping("/users/{id}")
public User getUser(@PathVariable Long id) {
return userService.findById(id);
}
}
Compiling Java with Annotations
javac -cp ".:lib/*" *.java && java -cp ".:lib/*" MainClass
My avatar

Thanks for reading my blog post! Feel free to check out my other posts or contact me via the social links in the footer.


More Posts

Comments