Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How @Target(ElementType.ANNOTATION_TYPE) works

Java annotations are marked with a @Target annotation to declare possible joinpoints which can be decorated by that annotation. Values TYPE, FIELD, METHOD, etc. of the ElementType enum are clear and simply understandable.

Question

WHY to use @Target(ANNOTATION_TYPE) value? What are the annotated annotations good for? What is their contribution? Give me an explanation of an idea how it works and why I should use it. Some already existing and well-known example of its usage would be great too.

like image 717
Gaim Avatar asked Feb 26 '13 22:02

Gaim


People also ask

What is ElementType Annotation_type?

@Target(ElementType. ANNOTATION_TYPE) it is a tool that allows to extend the use of annotations. Follow this answer to receive notifications.

What is the use of @target annotation?

This @Target meta-annotation indicates that the declared type is intended solely for use as a member type in complex annotation type declarations. It cannot be used to annotate anything directly: @Target({}) public @interface MemberType { ... }

Why are annotations used?

Annotations have a number of uses, among them: Information for the compiler — Annotations can be used by the compiler to detect errors or suppress warnings. Compile-time and deployment-time processing — Software tools can process annotation information to generate code, XML files, and so forth.

What is retention annotation?

Annotation Type RetentionIndicates how long annotations with the annotated type are to be retained. If no Retention annotation is present on an annotation type declaration, the retention policy defaults to RetentionPolicy. CLASS .


1 Answers

You can use an annotated annotation to create a meta-annotation, for example consider this usage of @Transactional in Spring:

/**  * Shortcut and more descriptive "alias" for {@code @Transactional(propagation = Propagation.MANDATORY)}.  */ @Target({ElementType.METHOD, ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) @Transactional(propagation = Propagation.MANDATORY) public @interface RequiresExistingTransaction { } 

When you enable Spring to process the @Transactional annotation, it will look for classes and methods that carry @Transactional or any meta-annotation of it (an annotation that is annotated with @Transactional).

Anyway this was just one concrete example how one can make use of an annotated annotation. I guess it's mostly frameworks like Spring where it makes sense to use them.

like image 106
zagyi Avatar answered Oct 09 '22 23:10

zagyi