Java core --- Annotation

Source: Internet
Author: User

Java core --- Annotation
Annotation is a new feature in jdk 5 and later versions. Spring and Hibernate frameworks provide annotation configuration methods. This article describes the annotations in the middle of the wave breeze and mainly explains the usage of jdk built-in annotations, the declaration and definition of annotations, as well as the usage of custom annotations are at the beginning, to say a little joke: <! -- Start --> I dreamed that my boyfriend and other women were shopping last night. In my dream, my first reaction was to check the source code... After debugging the results, I couldn't find out why the woman was not me. I finally commented out the woman with tears. Another trip was my boyfriend's own shopping... I woke up and spent a long time in my face... Author rz comment: 1L points the pointer of the woman to you. 2L who asked you to set your boyfriend to public 3L and add a breakpoint to see who the woman is. 4L is really soft, the interface should be blocked. // Is it I want more? 5L protected (youOnly) 6L design problems, the single-sample mode 7L is not used for regression testing. The 8L standard practice is to make an assertion 9L comment out the parameters of shopping. Do not change 10L. Do not forget GC. Thank you 11L for checking the Log. Do you only want to go shopping /. ** you can see one of the hardest replies: Well, you can use goto to create an endless loop and let them go to death. <! -- END --> many programmers who have written java code use annotations, but they only know some details. For example, annotations are for people and annotations are for the compiler; add a commonly used annotation such as @ Override and @ SuppressWarnings. We will provide a detailed description: 1. New Features after jdk5, annotation in java applications, we often encounter some situations where the template code is used, for example, to compile a web service, we must provide an interface and implementation as template code. If annotation is used to modify the remote access method, this template can be automatically generated using tools, some APIs need to maintain the ancillary files simultaneously with program code. For example, EJB requires a deployment descriptor. At this time, annotation is used in the program to maintain the information of these ancillary files, which is very convenient and reduces the built-in annotations of the wrong jdk, Override, Deprecated, SuppressWarnings @ Override, the method of forcibly checking the subclass overwrites the method of the parent class/Annotation/src/yuki/corejava/annotation/jdk5/OverrideTest. the class below java overrides the toString () method in the parent class Object to copy the code package yuki. corejava. annotation. jdk5; public class OverrideTest {@ Override public String toString () {return "This is override";} public static void main (String [] args) {OverrideTes T test = new OverrideTest (); System. out. println (test. toString () ;}} since the release of Java 5.0, the platform provides a formal annotation function that allows developers to define, use your own annotation type. This function reads the annotation API by a syntax defining the annotation type and a syntax describing the annotation Declaration, and a class file decorated with annotation, an annotation processing tool (apt) makes up annotation and does not directly affect the semantics of the Code, however, it can work in a way that is seen as a tool or class library similar to a program. In turn, it has an impact on the running program semantics. annotation can be reflected from the source file, class file, or at runtime. multiple read methods, of course, to some extent, annotation makes the javadoc tag more complete. A tag may affect the java document or be used to generate a java document as a javadoc tag. Otherwise, it will be used as an annotation to limit the Override parent class method @ Overridejava. lang. override is a marker annotation. Its function is to make the compiler check that the following method must be a rewrite method. Otherwise, the compiler reports an error, indicating that @ Deprecatedjava is not recommended for a method. lang. deprecated is a marker annotation/Annotation/src/yuki/corejava/annotation/jdk5/DeprecatedTest. java copy code package yuki. corejava. annotation. jdk5; public class DeprecatedTest {@ Deprecated public void doSomeT Hing () {System. out. println ("do some thing");} public static void main (String [] args) {DeprecatedTest test = new DeprecatedTest (); test. doSomeThing () ;}} copy the code. When the Child class inherits the parent class, override the obsolete method of the parent class, the Development Environment reports a warning/Annotation/src/yuki/corejava/annotation/jdk5/SubDeprecatedTest. java copy code package yuki. corejava. annotation. jdk5; public class SubDeprecatedTest extends DeprecatedTest {@ SuppressWarnings ("deprecation") @ Override Public void doSomeThing () {System. out. println ("do some thing in sub class");} copy the Code. If no warning is reported, you can press the check box below to suppress the compile program warning @ SuppressWarnings to explain to the compile program if a warning message exists in a method, then, it is blocked by/Annotation/src/yuki/corejava/annotation/jdk5/SuppressWarningsTest. java copy code package yuki. corejava. annotation. JDK 5; import java. util. date; import java. util. map; import java. util. treeMap; public class SuppressWarningsTest {@ SuppressWarnings ({" Unchecked "," rawtypes "," deprecation "}) public static void main (String [] args) {Map map = new TreeMap (); map. put ("hello", new Date (); System. out. println (map. get ("hello"); DeprecatedTest test = new DeprecatedTest (); test. doSomeThing () ;}} copy code 2. a custom Annotation @ interface can define an Annotation with an Attribute before a method or before a class or on a property, define an attribute value. If the attribute name is not a value, you must explicitly define the string as a special case in the string array. Therefore, you can copy the attribute value to the array. Just like the interface definition, only the Declaration does not implement a default value for the string/Annotation/src/yuki/corejava/annotation/define/p1/AnnotationTest. java copy code package yuki. corejava. annotation. define. p1; public @ interface AnnotationTest {// String value1 (); // String value (); // String [] value (); String value () default "default string";} copy the code/Annotation/src/yuki/corejava/annotation/define/p1/AnnotationUsage. java copy code package yuki. corejava. annotation. defin E. p1; public class AnnotationUsage {// @ AnnotationTest (value1 = "hello world") // @ AnnotationTest ("hello world") @ AnnotationTest public void method () {System. out. println ("usage of annotation");} public static void main (String [] args) {AnnotationUsage usage = new AnnotationUsage (); usage. method () ;}} the copy code can use enumeration to define some fixed alternative values. enumeration can be defined in the method. For convenience, defines a public enumeration/Annotation/src/yuki/corejava/annotation/d Efine/p2/EnumTest. java package yuki. corejava. annotation. define. p2; public enum EnumTest {Hello, World, Welcome}/Annotation/src/yuki/corejava/annotation/define/p2/AnnotationTest. java copy code package yuki. corejava. annotation. define. p2; public @ interface AnnotationTest {EnumTest value1 () default EnumTest. hello;} copy the code/Annotation/src/yuki/corejava/annotation/define/p2/AnnotationUsage. java copy code package yu Ki. corejava. annotation. define. p2; public class AnnotationUsage {// @ AnnotationTest (value1 = EnumTest. hello) @ AnnotationTest public void method () {System. out. println ("usage of annotation");} public static void main (String [] args) {AnnotationUsage usage = new AnnotationUsage (); usage. method (); System. out. println (EnumTest. hello) ;}} copy the running result of the Code main function and output the following content on the console: 12 usage of annotationHello use @ interfa When the ce custom Annotation type is defined, java is automatically and implicitly inherited. lang. annotation. the Annotation interface is automatically completed by the compiler. If other details are explicitly inherited from the Annotation interface, it is just a declaration of a common interface annotation type and cannot explicitly inherit the parent interface to inform the compiler how to handle @ Retentionjava. lang. annotation. the Retention type can indicate how the compiler treats your custom Annotation type when defining the Annotation type. the class file is not read by the virtual machine, but only used to compile the program or provide information when the tool is running. When using the Retention type, java is required. lang, annotation. public enum RetentionPolicy {SOURCE, // The compiled program has been processed Annotation completes the task CLASS, // The Compilation Program stores Annotation in the class, and the default RUNTIME // Compilation Program stores Annotation in the class, read by VM}/Annotation/src/yuki/corejava/annotation/define/MyAnnotation. java copy code package yuki. corejava. annotation. define; import java. lang. annotation. retention; import java. lang. annotation. retentionPolicy; @ Retention (RetentionPolicy. RUNTIME) public @ interface MyAnnotation {String hello () default "default hello "; String world ();} the example of copying the code RetentionPolicy as SOURCE is @ SuppressWarnings, which only notifies the compiler at compilation to suppress warnings, so this information is not stored in. when the RetentionPolicy of the class file is RUNTIME, it may be like using Java to design a program code analysis tool that requires the VM to read Annotation information, so that the reflection mechanism can be used in process analysis programs, in this way, the Annotation information can be read during the runtime and the Annotation attributes can be obtained through reflection. These attributes are used in Hibernate and Spring, with Annotations, you can easily configure and retrieve all annotations before the method to traverse/Annotation/src/yuki/corejava/annotation/define/MyReflection. java copy code package yuki. corejava. annotation. define; imp Ort java. lang. annotation. annotation; import java. lang. reflect. method; public class MyReflection {public static void main (String [] args) throws Exception {MyTest myTest = new MyTest (); Class <MyTest> c = MyTest. class; Method method = c. getMethod ("output", new Class [] {}); if (method. isAnnotationPresent (MyAnnotation. class) {method. invoke (myTest, new Object [] {}); MyAnnotation myAnnotation = method. get Annotation (MyAnnotation. class); String hello = myAnnotation. hello (); String world = myAnnotation. world (); System. out. println (hello); System. out. println (world);} Annotation [] annotations = method. getAnnotations (); for (Annotation annotation: annotations) {System. out. println (annotation. annotationType (). getName () ;}} copy the code/Annotation/src/yuki/corejava/annotation/define/MyTest. java copy code package yuk I. corejava. annotation. define; public class MyTest {@ MyAnnotation (hello = "beijing", world = "shanghai") @ Deprecated // @ SuppressWarnings ("unchecked") public void output () {System. out. println ("output something") ;}} copy the code running result as follows and get the right value of the attribute in the annotation -- "beijing ", "shanghai" traverses all RUNTIME annotations except this method 12345 output somethingbeijingshanghaiyuki. corejava. annotation. define. myAnnotationjava. lang. deprecated tells the compiler how to handle it @ Ret Entionjava. lang. reflect. when defining Annotation, The annottionpolicy must be set to RUNTIME to read Annotation information in the VM. Because @ SuppressWarnings has @ Retention (RetentionPolicy. SOURCE) So after compilation, there is no Retention value when RetentionPolicy. CLASS, the annotation information is only in. the class file exists, but it will not be read/Annotation/src/yuki/corejava/annotation/define/p4/EnumTest. java copy code package yuki. corejava. annotation. define. p4; public enum EnumTest {HELLO, WORLD, welcome} copy the code/ Annotation/src/yuki/corejava/annotation/define/p4/AnnotationTest. java copy code package yuki. corejava. annotation. define. p4; public @ interface AnnotationTest {EnumTest value1 () default EnumTest. HELLO; String value2 (); Class <?> C (); // Date date ();} when the code is declared, the compiler prompts the following results: 123 Invalid type Date for the annotation attribute AnnotationTest. date; only primitive type, String, Class, annotation, enumeration are permitted or 1-dimen1_arrays thereofInvalid type Date for the annotation attribute AnnotationTest. date; only primitive type, String, Class, annotation, enumeration are permitted or 1-dimen1_arrays thereof that is to say, only basic types, strings, classes, annotations, enumeration can be defined, and their one-dimensional arrays 3. Target, incluented, and Inherited restrict @ Target of annotation objects to use java. lang. annotation. target can define the time when it is used. If the Target is not added, the annotation can define the java. lang. annotation. public enum ElementType {TYPE, // class, interface, enum METHOD, // method PARAMETER, // parameter of method CONSTRUCTOR, // constructor LOCAL_VARIABLE, // local varible ANNOTATION_TYPE, // annotation PACKAGE // package} if the location of the annotation is not correct, the following warning is given: 1The annotation @ MyTarget is disallowed for this location/Annotation/src/yuki/corejava/annotation/define/target/MyTarget. java copy code package yuki.corejava.annotation.define.tar get; import java. lang. annotation. elementType; import java. lang. annotation. target; @ Target (ElementType. METHOD) public @ interface MyTarget {String value ();} copy the code/Annotation/src/yuki/corejava/annotation/define/target/MyTargetTest. java copy code package yuki.corejava.annotation.define.tar get; // @ MyTarget ("value") public class MyTargetTest {@ MyTarget ("value") public void doSomeThing () {System. out. println ("do some thing");} the copied Code requires that the API file @ deleented be used to add the Annotation message to the API when the user creates a JavaDoc file. lang. annotation. incluented/Annotation/src/yuki/corejava/annotation/define/doc/DocumentAnnotation. java copy code package yuki.corejava.annotation.define.doc; import java. lang. annotation. documented; @ Documentedpublic @ interface DocumentAnnotation {String hello ();} copy the code/Annotation/src/yuki/corejava/annotation/define/doc/DocumentTest. java replication code package yuki.corejava.annotation.define.doc; public class DocumentTest {/*** This is comments that I have added */@ DocumentAnnotation (hello = "welcome") public void method () {System. out. println ("hello world ");}}

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.