Java Learning Series (21) Java Object-oriented annotation

Source: Internet
Author: User


Reprint Please specify Source:http://blog.csdn.net/lhy_ycu/article/details/45295947


First, preface

The annotations annotation in Java are used in many ways, such as @test, Spring, SPRINGMVC, and other frameworks in the previously spoken unit tests. Java itself has a number of annotations, such as: @Override (subclass to rewrite/overwrite the corresponding method of the parent class), @Deprecated (indicating that the method is not recommended for use), @SuppressWarnings (suppress warning), and so on. Of course, we can also customize some of the annotations we need (usually in packages, classes, fields, methods, method parameters, and local variables), which requires four meta annotations from Java to complete our custom annotation functionality. Overall, the annotation comparison is still simple. Let's take a look at these four meta annotations:


Two or four types of meta annotations (source network)

(a) @Target
@Target indicates where the annotation is used, the desirable values are:
Elemenettype.constructor Constructor Declaration
Elemenettype.field field declarations (including Enum instances)
Elemenettype.local_variable local variable declaration
Elemenettype.method Method declaration
Elemenettype.package Package Declaration
Elemenettype.parameter parameter declaration
Elemenettype.type class, interface (including annotation type) or enum declaration
Elementtype.annotation_type annotations

(b) @Retention
@Retention indicates at what level the annotation information is saved. The optional retentionpolicy parameters include:
Retentionpolicy.source annotations will be discarded by the compiler
Retentionpolicy.class annotations are available in the CLASS file, but are discarded by the VM
The Retentionpolicy.runtime JVM also retains annotations at run time, so the information of the annotations can be read through the reflection mechanism.

(c) @Documented
@Documented include this annotation in Javadoc

(iv) @Inherited
@Inherited allow subclasses to inherit annotations from the parent class


Iii. Illustrative Example 1) annotations on the class
The compiler will record the annotation information in the class file, and the JVM retains annotations when running the Java program, so the information of the annotations can be read through the reflection mechanism. @Retention (retentionpolicy.runtime)//annotation function above class @target (elementtype.type) public @interface ClassName {//declaration default value string Name () default "Bean";//Special value string value ();}

2) annotations that Act on a property (field)
@Retention (retentionpolicy.runtime)//Annotation function @target (Elementtype.field) public on the Property (field) @interface FieldName {String Value ();}

3) Notes on the method of action
@Retention (retentionpolicy.runtime)//Annotation function on method @target (elementtype.method) public @interface MethodName {String value (); Class<?> type ();}

4) Example Demo

Import Java.lang.reflect.field;import java.lang.reflect.method;/** * @author [* Reproduced yesterday *] [email protected] * @since Version 1.0 * @datetime April 27, 2015 12:57:03 *///specifies which custom annotation class is used, and if name is removed, the name defaults to: Bean @classname (name = "Entity", value = "User" public class User {@FieldName ("name") private string name; @FieldName ("Gender") private string Sex;public string GetName () { return name; @MethodName (type = java.lang.String.class, value = "Harry") public void SetName (String name) {this.name = name;} Public String Getsex () {return sex;} @MethodName (type = java.lang.String.class, value = "male") public void Setsex (String sex) {this.sex = sex;} @Overridepublic String toString () {return "User [name=" + name + ", sex=" + Sex + "]";} public static void Main (string[] args) throws Exception {class<?> C1 = class.forname ("Com.leo.annotation.User");// class<?> C1 = student.class;//One: Gets the annotation information on the class//if annotations of the specified annotation type for the element exist on this object, the annotations are returned, otherwise nullclassname CN = C1.getannotation (Classname.class); System.out.println (Cn.name () + "," + Cn.value ()); System.out.println ("\n=============================");//Two: Gets the annotation information on the Property (field) field F1 = C1.getdeclaredfield ("Sex"); F1.setaccessible (TRUE); FIELDNAME fn = f1.getannotation (Fieldname.class); System.out.println (Fn.value ());//field[] field = C1.getdeclaredfields ();//For (Field field:fields) {//Field.setacce Ssible (TRUE);//FieldName fn = field.getannotation (fieldname.class);/if (fn! = null) {//System.out.println (Fn.value () );//}//}//Three: Gets the annotation information on the method method[] methods = C1.getdeclaredmethods (); User obj = (user) c1.newinstance (), for (method Method:methods) {System.out.println ("Methods name:" + method.getname ());//check method above is No annotationmethodname mn = Method.getannotation (Methodname.class), if (MN! = null) {//callback assignment. The first parameter is the target object, the second parameter is the method argument method.invoke accessed (obj, Mn.value ());}} System.out.println (Obj.getname () + "," + obj.getsex ());}}

Iv. Summary

1) Note: Annotations are not comments. Annotations provide an important part of implementing program functionality, while annotations provide a description of the code's capabilities.

2) annotations Enable the Java source code to include not only the functional implementation code, but also the metadata can be added.


Java Learning Series (21) Java Object-oriented annotation

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.