Code
import java.lang.annotation.*;// Simple annotation@Retention(RetentionPolicy.RUNTIME)@Target(ElementType.METHOD)public @interface LogExecution {}// Annotation with parameters@Retention(RetentionPolicy.RUNTIME)@Target({ElementType.METHOD, ElementType.TYPE})public @interface Author { String name(); String date() default "2024-01-01"; String[] tags() default {};}// Marker annotation@Retention(RetentionPolicy.RUNTIME)@Target(ElementType.TYPE)public @interface Serializable {}// Single-value annotation@Retention(RetentionPolicy.RUNTIME)@Target(ElementType.FIELD)public @interface MaxLength { int value();}// Annotation with enum parameterpublic enum Priority { LOW, MEDIUM, HIGH}@Retention(RetentionPolicy.RUNTIME)@Target(ElementType.METHOD)public @interface Scheduled { Priority priority() default Priority.MEDIUM; int interval() default 60;}// Using annotations@Author(name = "John Doe", tags = {"utility", "helper"})public class UtilityClass { @LogExecution @Scheduled(priority = Priority.HIGH, interval = 30) public void performTask() { // Method implementation } @MaxLength(100) private String description;}// Annotation processorpublic class AnnotationProcessor { public static void processAnnotations(Object obj) { Class<?> clazz = obj.getClass(); if (clazz.isAnnotationPresent(Author.class)) { Author author = clazz.getAnnotation(Author.class); System.out.println("Author: " + author.name()); } for (var method : clazz.getMethods()) { if (method.isAnnotationPresent(LogExecution.class)) { System.out.println("Logging execution of: " + method.getName()); } } }}// Built-in annotations@Overridepublic String toString() { return "Custom toString";}@Deprecatedpublic void oldMethod() { // Deprecated method}@SuppressWarnings("unchecked")public void suppressWarning() { // Code with unchecked warnings}@FunctionalInterfaceinterface Calculator { int calculate(int a, int b);}// Using custom annotations@Author(name = "Alice", date = "2024-01-15", tags = {"api", "v1"})public class ApiService { @LogExecution @Scheduled(priority = Priority.HIGH) public void processData() { // Method implementation } @MaxLength(255) private String apiKey;}// Processing annotations at runtimeClass<?> clazz = ApiService.class;if (clazz.isAnnotationPresent(Author.class)) { Author author = clazz.getAnnotation(Author.class); System.out.println("Author: " + author.name()); System.out.println("Tags: " + Arrays.toString(author.tags()));}// Get method annotationsfor (var method : clazz.getMethods()) { if (method.isAnnotationPresent(Scheduled.class)) { Scheduled scheduled = method.getAnnotation(Scheduled.class); System.out.println("Method " + method.getName() + " priority: " + scheduled.priority()); }}
Comments
No comments yet. Be the first!
Please login to leave a comment.