JohnJohnGa
JohnJohnGa

Reputation: 15685

Annotation SOURCE Retention Policy

From the Java doc:

CLASS: Annotations are to be recorded in the class file by the compiler but need not be retained by the VM at run time.

RUNTIME: Annotations are to be recorded in the class file by the compiler and retained by the VM at run time, so they may be read reflectively.

SOURCE: Annotations are to be discarded by the compiler.

I understand the usages of RUNTIME (in order to use annotation with reflection) and CLASS (for the compiler) but I don't understand when it can be usefull to use

@Retention(RetentionPolicy.SOURCE)

Can you explain?

Upvotes: 29

Views: 16113

Answers (3)

Yuresh Karunanayake
Yuresh Karunanayake

Reputation: 567

RetentionPolicy.CLASS - The defined annotation will be stored in the .class file, but not available at runtime. This is the default retention policy if you do not specify any retention policy at all.

RetentionPolicy.SOURCE - The defined annotation will be ignored by the compiler when building the code. So the annotation is only available in the source code, and not in the .class files, and not at runtime too.

Upvotes: -1

Manojkumar Khotele
Manojkumar Khotele

Reputation: 1019

This answer makes perfect sense - https://stackoverflow.com/a/43910948/3009968.

You would not like to include a dependency, the desired effects of which are realized even before the code is compiled. E.g. @SuppressWarnings

You would not like to include a dependency which is used by compiler to let's say generate code but not at all required during runtime. E.g. as mentioned already in previous answer -spring roo.

Upvotes: 0

gkamal
gkamal

Reputation: 21000

Things like @SuppressWarnings, @Override are annotations used by the compiler - not needed at runtime. For those RetentionPolicy.SOURCE would make sense. Also annotations can be used to generate code (look at Spring ROO) - such annotation are also not required at run time.

Upvotes: 28

Related Questions