In-depth understanding of Java annotations: use of annotations

Source: Internet
Author: User

annotations are the new features of jdk1.5. As we all know, jdk1.5 has epoch-making significance in the history of Java. The appearance of annotations has, to some extent, subverted the design of the framework. For example, spring has improved the pattern of the original five components after the annotations appear, Added annotation-based implementations. Now focus on the use of annotations.

meta-annotations:

The jdk1.5 defines 4 meta-annotations, which are annotated by annotating other annotations.

[Email protected]

[Email protected]

[Email protected]

[Email protected]

@Retention is used to indicate when the annotation exists. The parameter has three values to choose from: The Retentionpolicy.source,retentionpolicy.class,retentionpolicy.runtime is available for selection. respectively: Annotations are retained in the source code, and annotations are preserved in bytecode files, and annotations are preserved at runtime.

The @Target is used to indicate the extent to which the annotation can function. For example, the parameter is set to Elementtype.type, which represents the class and interface. If you are using the annotation method, a compilation error occurs. This shows that the function is implemented by the compiler.

@Documented indicates that the annotations are also included when generating the development document using the Javadoc tool.

@Inherited indicate that a location uses this annotation, the annotation can also be inherited where there is a Java inheritance relationship. This may not be easy to understand. The following code describes it.

1 @Retention (retentionpolicy.runtime) 2 @Target ({elementtype.type,elementtype.method}) 3 @Inherited 4  public @Interface  annoinherited {5     6 }

Test code:

1  Public classtestannoinherated {2      Public Static voidMain (string[] args) {3Annotation[] Annos=NewGoo (). GetClass (). Getannotations ();4          for(Annotation a:annos) {5 System.out.println (a);6         }7     }8 }9 Ten @AnnoInherited One classfoo{ A      - } -  the classGooextendsfoo{ -      -}

Console output:

@test. annotation.annoinherited ()

In the example above, Goo is not annotated @annoinherited, but the parent class Foo is preceded by, and @annoinherited adds the meta annotation @inherited, so foo can inherit.

Custom Annotations:

Examples of custom annotations are as follows.

 Packagetest.annotation;Importjava.lang.annotation.Documented;ImportJava.lang.annotation.ElementType;Importjava.lang.annotation.Retention;ImportJava.lang.annotation.RetentionPolicy;ImportJava.lang.annotation.Target, @Target (elementtype.type) @Retention (retentionpolicy.runtime) @Documented Public@InterfaceAnimalinfo {String shout ()default""; //can the Janitor    BooleanIsguard ()default true;}

Test code:

 Public classTestanimalinfo { Public Static voidMain (string[] args) {Animal Animal=NewAnimal (); Animalinfo Info=animal.getclass (). Getannotation (Animalinfo.class); if(info!=NULL) {Annotation anno=info;//There are no errors here. annotation is an interface. info is an annotation. This is because the compiler compiles annotations into interfaces and inherits the annotationSystem.out.println ("Annotation class Information:" +annotation.class); System.out.println ("Animalinfo class Information:" +animalinfo.class); Class[] CS=animalinfo.class. Getinterfaces ();  for(Class c:cs) {System.out.println (c); //Animalinfo compiled is an interface, and inherited the annotation, here is confirmed.} System.out.println ("Info object's class information:" +Info.getclass ()); if("Wangwang". Equals (Info.shout ()) &&Info.isguard ()) {System.out.println ("The animal is a dog"); }Else if("Miaomiao". Equals (Info.shout ()) &&!Info.isguard ()) {System.out.println ("The animal is a cat"); }Else{System.out.println ("The animal is not a dog or cat"); }        }Else{System.out.println ("It ' s not a animal"); }}} @AnimalInfo (Shout= "Wangwang", isguard=true)classanimal{}

Console output:

Annotation class information:interface  java.lang.annotation.AnnotationAnimalInfo class information:interface  Test.annotation.AnimalInfoInterface  Java.lang.annotation.Annotationinfo object class Info:class  com.sun.proxy. $Proxy 1the Animal is a dog

Code Analysis: From the console can see [email protected] annotations actually compiled is the interface, and it inherits the Annnotation. The annotated instance obtained by reflection, named $proxy1, is the object of a class. Visible, This annotation instance is generated by the JVM through dynamic agent technology. This also reveals the underlying implementation principle of the annotation feature. The specific underlying technical principles of annotations are not discussed here.

In-depth understanding of Java annotations: use of annotations

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.