When are Java annotations executed?

Actually, when you define an annotation, you must specify the parameter @Retention, which defines whether the annotation is available in the source code (SOURCE), in the class files (CLASS), or at run time (RUNTIME).

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

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


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.