Annotation (annotation) in Java

Source: Internet
Author: User
What is annotation? (Annotation or annotation)

Annotation, accurate translation should be -- Annotation. The function is totally different from that of annotations.

Annotation is a feature introduced in jdk5.0 and later versions. Classes, interfaces, and enumerations are at the same level and can be Java types.

The syntax starts @.

To put it simply,

Annotations are some memory or suggestive descriptions of the programmer's source code class, method, and attribute (for example, what is the use of this method.

Annotations are a part that the Java compiler can understand. They are for the compiler.

Let's take a simple example to illustrate the usage and functions of annotations.

@ Override is a common built-in JAVA annotation. Its function is to check whether the methods defined in the subclass are correct during code compilation.

package annotation;public abstract class Animal {public abstract void eat();}

package annotation;public class Cat extends Animal{@Overridepublic void eat(String food) {}}

In cat, the Eat method of the subclass is annotated as a method that overwrites the parent class, but it has one more parameter than the parent class method.

If you are editing it in eclipse, a Red Cross is prompted. (Code compilation fails ).

If the @ override annotation is removed, compilation is fine, but the Eat method in cat is a new method of this class, rather than inherited from the parent class.

Common Java built-in annotations

Including @ override, what are common Java built-in annotations?

1. @ deprecated

Annotations are not recommended and can be used in methods and classes.

Basically, this method and class are not recommended because of upgrades or performance reasons, but must be retained for compatibility or other reasons.

Therefore, add this annotation.

There are many such examples in the Java API. The method is annotated with this annotation, and the new alternative method will be seen in the source code.

When you write code in eclipse, the methods that add this annotation add strikethrough lines in the declaration and call fields.

2. @ override

3. @ suppresswarnings

Ignore warnings.

If your code has some warnings in the transformation or other part, but you want to ignore these warnings, you can use this annotation.

1) warning when deprecation uses a class or method that is not in favor of use

2) warning when unchecked performs unchecked Conversion

3) fallthrough warning when the case is not added to the break operation when the switch operation is used, and the program continues to execute other case statements

(4) warning when an incorrect class path or source file path is set in Path

5) Serial warning when serialversionuid definition is missing on serializable classes

6) warning when any finally clause in fianally cannot be completed normally

7) All warnings about all the above situations

Custom Annotation

In addition to the built-in annotations provided by Java, Java also provides custom annotations.

The method of definition is to use annotations to define annotations, which are called meta annotations.

The main element annotations are as follows: @ target; @ retention; @ incluented; @ inherited

1. @ target indicates the place where the annotation is used, used on the class, method, or attribute.

Possible elemenettype parameters include:
Elemenettype. constructor Declaration
Elemenettype. Field field Declaration (including Enum instances)
Elemenettype. local_variable local variable Declaration
Elemenettype. Method method declaration
Elemenettype. Package package Declaration
Elemenettype. Parameter parameter Declaration
Elemenettype. Type class, interface (including annotation type) or enum Declaration

2. @ retention indicates the level at which the annotation information is saved.

Optional retentionpolicy parameters include:
The retentionpolicy. Source annotation will be discarded by the compiler.
The retentionpolicy. Class annotation is available in the class file, but is discarded by the VM.
Retentionpolicy. runtime VM also retains annotations during runtime, so the annotation information can be read through the reflection mechanism.

3. @ brief ented: indicates whether the annotation is included when a doc is generated.

Include this annotation in javadoc

4. @ inherited

Allow subclass to inherit the annotation in the parent class

Let's look at some simple examples:

package annotation;import java.lang.annotation.Documented;import java.lang.annotation.ElementType;import java.lang.annotation.Inherited;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.annotation.Target;@Target(ElementType.METHOD)public @interface MyAnnotation {String value();}@Retention(RetentionPolicy.SOURCE) @interface MyAnnotation1 { } @Retention(RetentionPolicy.CLASS) @interface MyAnnotation2 {} @Retention(RetentionPolicy.RUNTIME) @interface MyAnnotation3 {}@Documented@interface MyAnnotation4 {}            @Inherited@interface MyAnnotation5 { }

Example:

package annotation;import java.lang.annotation.Annotation;@MyAnnotation3public class TestAnnotation {public static void main(String[] args) {// TODO Auto-generated method stubAnnotation annotation = TestAnnotation.class.getAnnotation(MyAnnotation3.class);System.out.println(annotation.toString());}}

Print the result: @ annotation. myannotation3 ()

In the preceding example, if myannotation1 and myannotation2 are used, the obtained annotation value is null. This is the difference between retentionpolicy and retentionpolicy.

Role of Annotation
Here, we can summarize the functions of annotation.
The basics can be roughly divided into three types:
1. Write documents
2. Code Analysis
3. Compilation check. However, the open-source framework gives it more functions.
For example:
Hibernate, annotation configuration,
@Column("aa")private String xx;

This is similar to xml configuration, which simplifies the configuration in the program.
Relatively, some metadata is moved from the XML file to the Code itself, and managed and maintained in one place.
How is it implemented internally? -- Java reflection mechanism, similar to the above example.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.