Retention Policy for Annotations in Java

Ashish Kumar
1 min readFeb 5, 2020

--

As we all know that Java Annotations are used to provide metadata for our code, typically used for the following purposes

  • Compile-Time Instructions
  • Build-Time Instructions
  • Run-Time Instructions

I am sure all of us must have used one or more of the built-in Java annotations like @Deprecated, @Override, @SuppressWarnings. But when it comes to creating our own annotation, say something like this

@interface WakeUpTheDevil {
String enchanchment();
int numberOfSacrifices();
}

By Default, this annotation is stored in the .class file & not available at the runtime. This is because of the default Retention Policy - RetentionPolicy.CLASS

What if we want our annotation to be available at runtime? Well, this is Java that we are talking about, Java allows us to specify this using RetentionPolicy.RUNTIME, which signals the compiler & the JVM that this annotation should be available via reflection at runtime.

But wait..what if I don’t want it at runtime, but I don’t want to pollute my .class file either? Java provides RetentionPolicy.SOURCE, which makes the annotation available only in the source code and not in the .class file or at runtime. Such annotations are used with build-tools that scan the file.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Ashish Kumar
Ashish Kumar

Written by Ashish Kumar

Engineer @Amazon | Open Source Enthusiast | Mentor Google Summer of Code’19 | Views are my own

No responses yet

Write a response