Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When are Java annotations executed?

I am just looking to write some annotation which can execute at runtime, before or immediately after a service method is invoked.

I don't know if they are executed at runtime or compile time.

like image 816
Chetan Avatar asked Feb 17 '12 16:02

Chetan


3 Answers

It depends on retention policy attached with that annotation.

A retention policy determines at what point annotation should be discarded. Java defined 3 types of retention policies through java.lang.annotation.RetentionPolicy enumeration. It has SOURCE, CLASS and RUNTIME.

  • Annotation with retention policy SOURCE will be retained only with source code, and discarded during compile time.

  • Annotation with retention policy CLASS will be retained till
    compiling the code, and discarded during runtime.

  • Annotation with retention policy RUNTIME will be available to the JVM through runtime.

The retention policy will be specified by using java built-in annotation @Retention, and we have to pass the retention policy type. The default retention policy type is CLASS.

like image 71
Shivang Agarwal Avatar answered Oct 01 '22 03:10

Shivang Agarwal


Annotations don't execute; they're notes or markers that are read by various tools. Some are read by your compiler, like @Override; others are embedded in the class files and read by tools like Hibernate at runtime. But they don't do anything themselves.

You might be thinking of assertions instead, which can be used to validate pre and post conditions.

like image 35
Ernest Friedman-Hill Avatar answered Oct 01 '22 03:10

Ernest Friedman-Hill


Annotations are just markers. They don't execute and do anything.

You can specify different retention policies:

  • SOURCE: annotation retained only in the source file and is discarded during compilation.
  • CLASS: annotation stored in the .class file during compilation, not available in the run time.
  • RUNTIME: annotation stored in the .class file and available in the run time.

More here: http://www.java2s.com/Tutorial/Java/0020__Language/SpecifyingaRetentionPolicy.htm

like image 29
Sarel Botha Avatar answered Oct 01 '22 03:10

Sarel Botha