Java Annotations (not annotations)

Source: Internet
Author: User
Tags deprecated reflection

This article will introduce you to one of the new features in j2se5.0: annotations. This article discusses the predefined annotations in annotations, j2se5.0, how to customize annotations, how to annotate annotations, and how to read annotations in a program in 5 ways.

One, what is annotation

Speaking of annotations, we have to mention what is metadata (metadata). The so-called meta data is data. In other words, the metadata is the description of the data. Like fields in a datasheet, each field describes the meaning of the data under this field. The annotations provided in j2se5.0 are the metadata of the Java source code, which means that the annotations describe Java source code. Annotations can be customized in j2se5.0. Use the name of the annotation following the @.

ii. predefined annotations in the j2se5.0

Three annotations have been predefined in the j2se5.0 Java.lang package. They are override, deprecated and suppresswarnings. The following are the meanings of each of these solutions.

Override

The function of this annotation is to identify whether a method overrides its parent class. So why do you want to identify it. Let's see what happens if you don't have to override the logo.

Assuming there are two classes of Class1 and ParentClass1, the ParentClass1 method in MyMethod1 is overwritten with the MyMethod1 method in Class1.


Class ParentClass1
{
public void MyMethod1 () {}
}

Class Class1 extends ParentClass1
{
public void MyMethod2 () {}
}


Creates an instance of the Class1 and calls the MyMethod1 method

ParentClass1 C1 = new Class1 ();

C1.mymethod1 ();

The code above can be compiled and run normally. However, when writing Class1 code, MYMETHOD1 was written in MyMethod2, but MyMethod1 was not overwritten when invoked. Therefore, the C1.MYMETHOD1 () call is the ParentClass1 MyMethod1 method. Unfortunately, programmers are not aware of this. Therefore, this can cause bugs.

If we use override to modify the MyMethod1 method in Class1, the compiler will complain when MYMETHOD1 is mistakenly written to another method. Therefore, this type of error can be avoided.

Class Class1 extends ParentClass1
{
@Override//compiler generates an error
public void MyMethod2 () {}
}


The above code compilation cannot pass, the method that is override annotation must exist the same method program in the parent class to compile the pass. This means that only the following code compiles correctly.

Class Class1 extends ParentClass1
{
@Override
public void MyMethod1 () {}
}


deprecated

This annotation is a markup annotation. labeled annotations, which are added to the source program, do not affect the program's compilation, but sometimes the compiler displays some warning messages.

So what does the deprecated annotation mean? If you frequently use Ides such as Eclipse to write Java programs, you may often see the word in a property or method hint. If a word appears in the prompts of a class member, it means that it is not recommended to use this class member. Because this class member may be deleted in a future JDK version. The reason why it is still retained is because of a buffer period for the programs that have already used these class members. If you go now, then these programs will not compile in the new compiler.

Speaking of which, you may have guessed it. Deprecated annotations must be related to these classes of members. That's right. After you use deprecated to annotate a class member, there will be some changes in the display of this class member. is very obvious in eclipse. Let's see what's changed in Figure 1.

Figure 1 plus the changes in eclipse of class members after @deprecated

As can be seen from the above picture, there are three changes happening in the area. The red box is the part of the change.

1. Method Definition Branch

2. Method Reference Place

3. Displayed in the list of members

These changes do not affect the compilation, just remind the programmer, this method is to be deleted, it is best not to use.

Deprecated annotations also have a role to play. Is that if a class inherits from another class and override the deprecated method of the inherited class, a warning will appear at compile time. The contents of the Test.java are as follows:

Class Class1
{
@Deprecated
public void MyMethod () {}
}

Class Class2 extends Class1
{
public void MyMethod () {}
}

Running Javac Test.java appears with the following warning:

Note: Test.java uses or overrides an outdated API.

Note: To get more information, use-xlint:deprecation to recompile

Use-xlint:deprecation to display more detailed warning information:

Test.java:4: Warning: MyMethod () in [deprecation] Class1 is obsolete

public void MyMethod ()

^

1 warning

These warnings do not affect compilation, just to remind you to try not to use the MyMethod method.


suppresswarnings

Things in this world always appear in pairs. If there is a warning message to the compiler, then there is a suppression compiler to generate a warning message.

Suppresswarnings annotations exist for such a purpose. Let's take a look at the following code first.

public void MyMethod ()
{
List wordlist = new ArrayList ();
Wordlist.add ("foo");
}


This is the method in a class. Compile it, you will get the following warning.

Note: Testannotation.java is using an unchecked or unsafe operation.

Note: To get more information, use-xlint:unchecked to recompile.

These two lines of warning messages indicate that the list class must use a generic to be safe for type checking. There are two ways to do this if you don't want to display this warning message. One is to rewrite the method as follows:


public void MyMethod ()
{
list<string> wordlist = new arraylist<string> ();
Wordlist.add ("foo");
}


Another way is to use @suppresswarnings.


@SuppressWarnings (value={"Unchecked"})
public void MyMethod ()
{
List wordlist = new ArrayList ();
Wordlist.add ("foo");
}


Note that suppresswarnings is not the same as the first two annotations. This annotation has an attribute. Of course, other warnings can also be suppressed, such as @suppresswarnings (value={"Unchecked", "Fallthrough"})

iii. How to customize annotations

The strength of annotations is that it can not only make Java programs self-describing, but also allow programmers to customize annotations. The definition of annotations is similar to the interface, just one more "@" in front of the interface.

Public @interface Myannotation

{

}

The code above is one of the simplest annotations. This annotation has no attributes. It can also be interpreted as a markup annotation. Just like the serializable interface is a markup interface, which does not define any methods.

Of course, you can also define annotations that have attributes.
Public @interface Myannotation

{
String value ();
}

You can use myannotation in the following format
@MyAnnotation ("abc")

public void MyMethod ()

{
}

Looking at the code above, you may have a question. Why not use value, and write "abc" directly. So, who did "ABC" Pass on to? There is actually an agreement here. If the value of the property name is not written, and the annotation has the value attribute, the value is assigned to the property, and if not, a compilation error occurs.

In addition to omitting property names, you can omit property values. This is the default value.
Public @interface Myannotation

{
Public String MyMethod () default "XYZ";
}

You can use Myannotation directly
@MyAnnotation//using default value XYZ

public void MyMethod ()

{

}

You can also use this
@MyAnnotation (mymethod= "abc")

public void MyMethod ()

{

}

If you want to use more than one attribute. You can refer to the following code.

Public @interface Myannotation
{
Public enum Myenum{a, B, C}
Public MyEnum value1 ();
Public String value2 ();

}

@MyAnnotation (VALUE1=MYANNOTATION.MYENUM.A, value2 = "xyz")
public void MyMethod ()
{
}


This section discusses how to customize annotations. So what's the use of defining annotations? Is there any way to limit annotations? Can we get an annotation from the program? These questions can be found in the following sections of the answer.

Iv. How to annotate annotations

The topic of this section is a bit of a detour, but the knowledge it contains is a great help in designing more powerful Java programs.

The custom annotations are discussed in the previous section, so we know that annotations are similar to classes and interfaces in j2se5.0. is a basic part of the program. Since you can annotate classes and interfaces, you can, of course, annotate annotations.

The method for annotating annotations using common annotations is the same as for annotating classes and interfaces. The difference is that j2se5.0 provides 4 annotations, namely meta annotations, for annotations alone. Meta-Annotation Understanding: Annotations can be used for annotation classes (annotate Classes) can be used for annotation interfaces (annotate interfaces) for annotation enumeration types (annotate Enums) so annotations can also be used for annotation annotations (annotate Annotations)

They are target, Retention, documented and inherited. The following 4 annotations are described separately.

Target

This annotation is very simple to understand. Since Target's Chinese meaning is "target", we may have guessed that the annotation is related to some objective. So what do these goals mean? You can look at the following code first.


@Target ({Elementtype.method})
@interface Myannotation {}

@MyAnnotation//Wrong use
public class Class1
{
@MyAnnotation//correct use
public void MyMethod1 () {}
}


The above code defines an annotation myannotation and a class Class1, and uses myannotation to annotate Class1 and MYMETHOD1 respectively. If you compile this code, you cannot pass it. Some people may be surprised, yes. But the problem is on @target ({Elementtype.method}), because Target uses an enumerated type property and its value is Elementtype.method. This means that myannotation can only be annotated as a method. It cannot be annotated for any other language element. Therefore, myannotation naturally can not be annotated for CLASS1.

Speaking of which, we may have understood the basics. The original target is the Java language element. such as classes, interfaces, methods, and so on. Of course, target can also restrict other language elements, such as constructors, fields, parameters, and so on. If you only allow annotations to methods and constructors, you can write:

@Target ({elementtype.method, elementtype.constructor})

@interface Myannotation {}

Retention

Since you can customize annotations, you can of course read annotations in the program (how to read the annotations will be discussed in the next section). But annotations can be read only if they are saved in a class file. and retention is the existence of setting annotations in a class file. The following code is a detailed usage of retention.

@Retention (Retentionpolicy.source)

@interface MyAnnotation1 {}

@Retention (Retentionpolicy.class)

@interface MyAnnotation2 {}

@Retention (Retentionpolicy.runtime)

@interface MyAnnotation3 {}

The first piece of code does not save annotations in a class file, which means they are filtered out at compile time like "//". The second piece of code is used to save annotations only in the class file and ignore them when reading annotations using reflection. The third piece of code is to keep annotations in the class file, or to read annotations through reflection.

documented

This annotation is related to the document as well as its name. By default, annotations are ignored when you automatically generate documents using Javadoc. If you want to include annotations in your document, you must use documented for document annotations.
@interface myannotation{}

@MyAnnotation
Class Class1
{
public void MyMethod () {}
}
Using Javadoc to generate documentation for this code does not include @myannotation. The resulting document describes the CLASS1 as follows:

Class Class1 extends Java.lang.Object

And if this definition myannotation, there will be another result.

@Documented

@interface Myannotation {}

Generated documents:

@MyAnnotation//This line was added after adding @documented.

Class Class1 extends Java.lang.Object

inherited

Inheritance is one of the main features of Java. Both the protected and the public members in the class will inherit the quilt class, but the parent class's annotation will not inherit from the quilt class. I regret to tell you that, by default, the annotations of the parent class are not inherited by the quilt class. If you want to inherit, you must add a inherited annotation.


@Inherited
@interface Myannotation {}

@MyAnnotation
public class ParentClass {}

public class ChildClass extends ParentClass {}


In the above code ChildClass and ParentClass have been myannotation annotated.

v. How to read annotations using reflection

The previous discussion discusses how to customize annotations. But what's the use of customizing annotations? This question is the key to j2se5.0 to provide annotations. Custom annotations are of course to be used. So how to use it. To solve this problem, you need to use one of the most exciting features of Java: Reflection (Reflect).

In previous versions of JDK, we could use reflection to get information such as the method of the class, the parameters of the method, and other class members. In j2se5.0, it is also possible to get all kinds of information about annotations in the same way as methods.

You must use the import java.lang.reflect.* to import and reflect related classes before using reflection.

If you want to get the annotation information for a class or interface, you can use the following code:

Annotation Annotation = TestAnnotation.class.getAnnotation (Myannotation.class);

If you want to get all the annotation information, you can use the following statement:

annotation[] annotations = TestAnnotation.class.getAnnotations ();

Or

annotation[] annotations = TestAnnotation.class.getDeclaredAnnotations ();

Getdeclaredannotations are similar to getannotations, but they are different getdeclaredannotations get all the annotations of the current member, excluding inherited. And Getannotations gets all the annotations that include inheritance.

If you want to get comments from other members, you can get the member first and then get the corresponding annotation. If you get a mymethod annotation.

Method method = TestAnnotation.class.getMethod ("MyMethod", null);

Annotation Annotation = method.getannotation (Myannotation.class);

Note: To use reflection to get annotation information, this annotation must use the

@Retention (retentionpolicy.runtime) for annotations.

vi. The nature of annotations: annotations are a type Types in JDK5.0:1, Class (Class) 2, Interface (interface) 3, enum (enum) 4, annotations (Annotation) Therefore, annotations, like other 3 types, can be defined, used, and contain their own properties, methods

vii. Annotation Classification: (1) Mark annotation: There is no attribute inside the annotation, called the mark Annotation use method: the @ annotation name uses the example: @MarkAnnotation (2) Single value annotation: The annotation's interior has only one attribute, is called the single value annotation use method: @ annotation Name (attribute name = Use example: @SingleAnnotation (value= "abc")//can also be written as @singleannotation ("abc") * (attribute name = attribute value) can be simplified to (property value), but the following two conditions are required: 1, The annotation must be a single value note 2, the attribute name of the annotation must be a value (3) multi-valued annotation: The annotation has multiple attributes inside it, called multivalued annotations: the @ Annotation Name (property name 1 = property value 1, property Name 2 = property value 2 ...) Use example: @MultipliedAnnotation (value1 = "abc", value2 = 30 ...)

Eight, automatic test machine writing: the principle of automatic testing machine:

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.