Java Foundation Strengthening-JDK1.5 new features-annotations

Source: Internet
Author: User
Tags code tag deprecated reflection

Java Foundation Enhancement-annotations

I. Definition of annotations

definition: annotation (Annotation) is a markup interface, the annotation is a new type of Java (similar to the interface), it and Class (Class), Interface (interface), enum (enum) is at the same level, the annotation is equivalent to a token, Adding a note to a program is tantamount to marking a program with some kind of markup, without it being equal to not having some kind of tag. We can define annotations, declare annotations, get annotations, and do the corresponding processing according to the annotations obtained, many of which have a large application of annotations.

Two. Understanding of Java.lang.Annotation

1. All defined annotation types are to inherit the annotation interface, and defining annotations requires the use of @interface.

2. Annotations Declare a format:

Permission modifiers @interface annotation class name {}

The following defines an annotation myannotation:

Public @interface myannotation
{
}

3. When annotations are defined, they can be used on parameters of packages, classes, fields, methods and methods, and on local variables.

4. When we define an annotation using the @interface keyword, the annotation implicitly inherits the Java.lang.annotation.Annotation interface; If we define an interface and let the interface inherit from annotation, The interfaces we define are still interfaces rather than annotations; The annotation itself is an interface, not an annotation. Can be analogous to the enum.

three. Add basic attributes for annotations

1. Attribute: A note is the equivalent of a chest card, but only through the chest card is not enough to distinguish the two people with a chest card, then need to add a property to the chest card to distinguish, such as color.

2. Define the format: Same as the method in the interface: Stringcolor ();

Defines the default format: String value () default "Heima";

3. Apply: Add your own attributes directly to the parentheses of the annotation, such as:

@MyAnnotation (color= "Red")

4. If you have a property named value in the note, and you want to set the Value property only (that is, if all other properties are in the default value or you have only one Value property), you can omit the value= section, for example: @SuppressWarnings (" Deprecation ").

5. You can specify a default value for the property value (default), and you can also reset the property value when applied.

four. Add advanced attributes for annotations

1. The return value types that can add advanced properties for annotations are:

A. Eight basic types of data

B. String type

C. Class type

D. Enumeration types

E. Types of annotations

F. Arrays of the first five types

2. Properties of array type

such as: Int[]arrayarr () Default {1,2,3};//does not define defaults

Apply: @MyAnnotation (arrayarr={2,3,4})//Can be re assignable

Note: If there is only one element in the array property (or the reassign is an element), then the property value section can omit the curly braces.

Public @interface myannotation
{
    int[] array ();
    Int[] Array2 () default {1,2,3};
    Int[] Array3 () default 2;
}

3. Attributes of enumerated types

Defined:

Public @interface myannotation
{
    int[] array ();
    Int[] Array2 () default {1,2,3};
    Int[] Array3 () default 2;
Color color ();//Enumeration Property
Enumtest. Trafficlamp lamp () default enumtest. Trafficlamp. RED 
}

Application:

@MyAnnotation (Lamp=enumtest.trafficlamp.blue,array={2,3,4},color=color.black)

4. Attributes of the annotation type
Suppose there is an annotation class: Metaannotation, which defines an attribute: StringValue ()

Definition: metaannotation annotation () default @MetaAnnotation ("xxx");
Application: @MyAnnotation (annotation= @MetaAnnotation ("yyy"))/assignable

Note: The above @metaannotation is considered to be an instance object of the Myannotation class, and the above @metaannotation can also be considered an instance object of the Metaannotation class, called: Metaannotationma =myannotation.annotation ();
System.out.println (Ma.value ());

5. Attribute of class type

Defined:

Public @interface myannotation
{
    int[] array ();
    Int[] Array2 () default {1,2,3};
    Int[] Array3 () default 2;
    Color color () default color.black;
    Class Clazz ();//define a class type attribute
}

Application:

@MyAnnotation (Array={2,3,4},clazz = weekdaytest.class)

Note: the. Class here must be a defined class, or an existing byte code object

6. properties of the basic data type (for example, int):

Defined:

Public @interface myannotation
{
    int[] array ();
    Int[] Array2 () default {1,2,3};
    Int[] Array3 () default 2;
    Color color () default color.black;
    Class clazz ();
    int Val ();//Set a property of the base data type
}

Application:

@MyAnnotation (Array={2,3,4},clazz = Weekdaytest.class, val=3)

Five. Three basic annotations in Java

 

1. @SuppressWarning ("deprecation"): to suppress outdated warnings; or not to warn you about outdated reminders.

Supresswarning is to tell the compiler or development tools, and so on without prompting the specified warning;

"Deprecation" is a warning message, which is an obsolete warning.

2. @Deprecated: Indicates to inform the caller that the member function, field, etc. is obsolete and is no longer recommended for use. The source code tag @deprecated is introduced as a built-in annotation in JDK1.5 to indicate that classes (class), methods (method), fields (field) are no longer recommended and may be deleted in future JDK versions. The compiler prompts for a warning message when it detects this tag by default.

For example , assuming that a previous class has been upgraded, one of the methods is obsolete and cannot be deleted because it may affect some of the programs that previously called this method, and then you can mark it by adding this annotation to the method.

3. @Override: means that the following method overrides the parent class method, and if there is no overwrite, an error occurs.

With this annotation, you can determine whether the method in the class is the method of the parent class to overwrite. A typical example is when the Equals (Object obj) method is overridden in a class, where the argument type must be Object to be overwritten, or no overwrite if not. If you add this annotation at this point, you will be prompted for a warning.

Six. Annotation Application Structure Chart

seven. Meta-annotations (annotations)

1. function:

The role of meta annotations is to use meta annotations when customizing annotations, meta-annotations, the value of these meta annotations is defined, you can tell the annotation is retained at what stage, such as the compiler, runtime, and so on, you can also tell the annotation to know what the target, such as only used in the method, can only be used on the class, and so on.

2. use meta Annotations to define annotations, with four of meta annotations:

A. @Target (elementtype.[ Type])
[Type]={method, FIELD, type (class, interface, enum declaration), constructor, Local_variable,parameter}

B. @Retention (retentionpolicy.[ Policy])
[Policy]={source (source file period), class (class file period, default phase), RUNTIME (runtime, reflection mechanism readable, such as @deprecated)}

The life week of an annotation has several states:

Java source Program--(JAVAC)-->class file--(ClassLoader)--> byte code in memory

First. When an annotation plus @Retention (retentionpolicy.source) annotation, javac the Java source program into a class file, may be the source of some of the annotations removed, to do the corresponding processing operations, When we get the source program, we don't see these annotations.

Second. When an annotation is added to the @Retention (retentionpolicy). Class) annotation, Suppose javac to leave these annotations in the source program (or stay in the class file), when running this class file, use class loader to transfer class file into memory, at this time there is the process of conversion, That is, the annotation in the class file is not necessarily retained.

Third. When an annotation is added to the @Retention (retentionpolicy). RUNTIME) Note, This annotation will be retained to the runtime, during which we can get the annotation information through reflection, which represents the value of the class is type. Because class, enum, interface, and @interface are all of type. cannot be expressed in class.

Note: The class file is not a byte code, only the class file in the internal load into the memory, with the class loader loading processing (for a complete inspection, etc.), the final binary content is the bytecode.

C. @Documented means to include this annotation in Javadoc

D. @Inherited represents annotations that allow subclasses to inherit the parent class

Eight. Practice

@MyAnnotation (Array={2,3,4},clazz = Enumtest.class, val=3) public class Enumtest {@MyAnnotation (val =-) public static
		        	   void Main (string[] args) {if (EnumTest.class.isAnnotationPresent (Myannotation.class)) {
		        	   Myannotation annotion = EnumTest.class.getAnnotation (Myannotation.class);
		        	   System.out.println (annotion);
		        	   System.out.println (Annotion.val ());
		        	   System.out.println (Annotion.array ());
		        	   System.out.println (Annotion.array2 ());
		        	   System.out.println (Annotion.array3 ());
		        	   System.out.println (Annotion.clazz ());
		           System.out.println (Annotion.color ());
}} import Java.lang.annotation.ElementType;
Import java.lang.annotation.Retention;
Import Java.lang.annotation.RetentionPolicy;
Import Java.lang.annotation.Target;
Keep Annotations to runtime @Retention (Retentionpolicy.runtime)})//@Target annotations on methods and classes ({Elementtype.type,elementtype.method Public @interface Myannotation {
    Int[] Array () default 25;
    Int[] Array2 () default {1,2,3};
    Int[] Array3 () default 2;
    Color color () default color.black;
    Class clazz () default color.class;
int Val ();
 public enum Color {Red,blue,black}















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.