j2se5.0 Instance---annotation (annotation)

Source: Internet
Author: User
Tags define definition command line comments deprecated interface modifier string
j2se Annotation (annotation)


J2SE 5.0 adds support for metadata by introducing the concept of annotations (Annotation).



A @xxx form of annotation can be used as a modifier, and it can be placed where any modifier can appear. Public,static,final are all modifiers of the Java language, and annotations can be written anywhere they can appear.



For example, take a look at the following code:



public class Annotationexample {



public @Override int Hashcode () {



return Super.hashcode ();



}



}



In this example we used a comment @override already defined in the Java language API, using this annotation in the method Hashcode () to show that Hashcode is a method that overrides the parent class method.



As for the specific meaning of the annotation, we will explain it in a later section.



If you want to use a class, you must first find its definition, or you may define it yourself. Annotations also need to be defined, and any comment that inserts a @xxx in your code cannot be compiled.



One of the simplest annotation definitions is similar to the definition of an interface, like the following code:



Public @interface Info {



}



As you can see, there is nothing in it, but even so, we could use it in a program:



public @Info String information;



Such a null annotation which has no definition of what we call a tag annotation (marker annotations).

We can add a definition of a member to it:

Public @interface Info {

String author ();

}

It is noteworthy here that the definition of the method in the annotation class cannot be private, and if you do not precede the public keyword, the compiler defaults to it as publicly owned.

After adding the definition of author, the original kind of comment that wrote only one @info must be modified, and the following note must write this:

Public @Info (author= "myname") void Afunction () {

}

A member of a note can have a default value:

Public @interface Info {

String author () default "MyName";

}

What are the benefits of using default values? We can write this again:

Public @Info void Afunction () {

}

When marking, if you confirm that a member's value is the same as its default value, we can ignore it without having to explicitly assign a value to each member, thus reducing the amount of code.

If the member name that we add is called value, that is:

Public @interface Info {

String value ();

}

There is another use of annotations: we can simply write the annotation @info ("information") without having to write @info (value= "Information"), and the values in parentheses are automatically passed to value. Such an annotation is called a single value annotation (single-value annotations)



A comment can have many different types of members, such as a complete annotation (full annotations).

A member type in a note can only be a primitive type, a string, a class type, an annotation type, an enumeration type, or a one-dimensional array.

Suppose we now have an annotation definition:

Public @interface Company {

String value ();

}

Now we want to define another annotation, which reflects a person's information:

Public @interface Person {

public enum Gender{male,female};



String name ();

int age ();

Company Company ();



Gender Gender () default Gender.male;

String description () default "";

}



You can write this type of comment when you add it to your program code:

@Person (age=23,name= "MyName", Gender=person.gender.female, company= @Company ("Foo Corporation")





Three types of annotations are defined in the Java.lang package, respectively:

N Deprecated: Same meaning as @deprecated in past Javadoc

N Override: The Representation method overrides the method in the parent class

N suppresswarnings: Use this annotation to cause the compiler to ignore specific types of warning messages

The specific meaning can refer to the API documentation.

As we know, the introduction of annotations adds metadata to the Java language, and metadata is data about the data. In Java, there are comments about annotations, which we call the Meta annotations (meta-annotations)



In Java, we can annotate annotation definitions with 4 predefined annotations, and the 4 types of comments are:



N Target: Indicates which code snippets the annotation can use in order to avoid misuse of annotations.



N Retention: Indicates whether the compiler ignores the annotation at compile and run time



N Documented: Indicates if the annotation appears in Javadoc



N Inherited: When we use some kind of annotation in a class, sometimes we want the annotation information to be included in all of its subclasses in the future, and if @inherited is added to the annotation definition, then the annotation is inherited by the caller's subclass



When we use annotations in a class to define a series of metadata, how do we get to these meta data? We use the following examples to illustrate.

The annotation definition still uses the two listed, because we need to get the annotation information in the class file, so we must add the retention annotation in the annotation definition.

First we define two comments, and the comment Todo explains what else needs to be done:

Import java.lang.annotation.Retention;

Import Java.lang.annotation.RetentionPolicy;





@Retention (Retentionpolicy.runtime)

Public @interface Todo {

String value ();

}

Note Author describes the definition of a method or class:

Import java.lang.annotation.Retention;

Import Java.lang.annotation.RetentionPolicy;





@Retention (Retentionpolicy.runtime)

Public @interface Author {

public enum Gender{male,female};





String name ();

String email ();

Gender Gender () default Gender.male;

}

Then we add the two types of annotations to a simple class:

Public @Todo (' Delete this class ') class Foo {



public void MethodA () {}

Public @Author (name= "B", email= "b@Foo.com") void MethodB () {

}



Public @Author (name= "A", email= "a@Foo.com") String Fielda;

}

The following section of the code allows us to extract the corresponding meta data:

Import Java.lang.reflect.Method;





public class Getannotations {





public static void Main (string[] args) {

try {

Class<?> Klass=class.forname (args[0]);

if (Klass.isannotationpresent (Todo.class))

{

Todo t=klass.getannotation (Todo.class);

System.out.println (t);

}

For (Method M:klass.getmethods ())

{

if (M.isannotationpresent (Author.class))

{

Author a=m.getannotation (Author.class);

System.out.printf ("method:%s,author:%s%n", M.getname (), a);

}

}

catch (ClassNotFoundException e) {



E.printstacktrace ();

}

}

}

Run the program using the following command line:

Java getannotations Foo

The results of the operation are as follows:

@Todo (Value=delete this class)



Method:methodb,author: @Author (Gender=male, name=b, email=b@foo.com)


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.