Retention Policy in Java Annotations

Something I keep forgetting, which I’m recording here so I can remember in the future.

When creating a new annotation which is to be parsed during execution with Java Reflection, you must change the retention policy with the @Retention annotation.

So, for example:

@Retention(RetentionPolicy.RUNTIME)
public @interface MyCustomAnnotation {
...
}

This will keep the annotation around when checking annotations at runtime.

For whatever reason I keep forgetting this.

Leave a comment