When are Java annotations executed?

I just want to write some annotation that can be executed at runtime, before or immediately after calling the service method.

I do not know if they are executed at runtime or compile time.

+6
source share
6 answers

Annotations are not executed; These are notes or markers that are read by various tools. Some of them are read by your compiler, for example @Override ; others are embedded in class files and read by tools like Hibernate at runtime. But they do nothing themselves.

Instead, you can think of statements that can be used to test pre and post conditions.

+9
source

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

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

Annotations are just markers. They do not do and do nothing.

You can specify various storage policies:

  • SOURCE: Annotation is saved only in the source file and discarded at compile time.
  • CLASS: An annotation stored in a .class file at compile time is not available at run time.
  • RUNTIME: An annotation stored in a .class file and available at run time.

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

+5
source

Annotations do not affect your code; they are intended to provide information to the compiler or other tools.

Annotations have a number of uses, including:

Information for the compiler. Annotations can be used by the compiler to detect errors or suppress warnings.

Compilation time and deployment time - software tools can process annotation information to generate code, XML files, etc.

Processing runtime. Some fragments are available for checking at runtime.

See page .

+2
source

In fact, they can be read in both environments, depending on the storage policy that you set.

0
source
  • Annotations are just markers in the source code. They will be used by tools such as IDEs, compilers, or annotation processors.

  • You can determine with @Retention if the annotation needs to be evaluated at the source, class, or runtime.

  • If you want to define your annotations, and only you know what the annotation should do, so you should write an annotation handler. (but it's not easy - maybe)

0
source

Source: https://habr.com/ru/post/908723/


All Articles