How do you use runtime retention policies with a simple code example?

An overview of using Java annotations with runtime retention policies, showcasing how they can be applied in a simple example.
Java, annotations, runtime retention policies, programming, example
import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.lang.annotation.ElementType; // Define a custom annotation with runtime retention policy @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface MyCustomAnnotation { String value(); } public class MyClass { @MyCustomAnnotation("This is a custom annotation") public void myAnnotatedMethod() { System.out.println("This method is annotated with MyCustomAnnotation."); } public void invokeAnnotation() { try { // Accessing the annotation at runtime MyCustomAnnotation annotation = this.getClass() .getMethod("myAnnotatedMethod") .getAnnotation(MyCustomAnnotation.class); if (annotation != null) { System.out.println("Annotation value: " + annotation.value()); } } catch (NoSuchMethodException e) { e.printStackTrace(); } } public static void main(String[] args) { MyClass myClass = new MyClass(); myClass.invokeAnnotation(); } }

Java annotations runtime retention policies programming example