Java annotation (annotation)

Source: Internet
Author: User

Java 5 provides new annotations to provide additional information for classes. This article describes how to define annotations, how to use annotations, and how to parse annotations.

1. Define comments

Package CH5;

Import java. Lang. annotation. elementtype;
Import java. Lang. annotation. retention;
Import java. Lang. annotation. retentionpolicy;
Import java. Lang. annotation. target;

// There are two types of Annotations: retentionpolicy. Runtime (which can be found during compilation and running ),
// Retentionpolicy. Source (ignored during compilation)
@ Retention (retentionpolicy. runtime)
// Target indicates where the annotation is used: On the class or interface (elementtype. type ),
// Method (elementtype. method ),
// Attribute (elementtype. Field)
@ Target ({elementtype. Type })
Public @ interface table {
String name ();
}

2. Use annotations

Package CH5;

@ Table (name = "user ")
Public class userbean {
Private string ID;
Private string name;
}

3. parse comments

Package CH5;

Import java. Lang. annotation. annotation;

Public class usermanger {
Private userbean user;
Public static void main (string [] ARGs ){
System. Out. println (New usermanger (). gettable ());
}
 
/*
* Obtain comments
*/
Public String gettable (){
// Get all comments
Annotation [] annotations = userbean. Class. getannotations ();
// Traverse
For (annotation: Annotations ){
// Check whether there are specific comments
If (annotation instanceof table ){
Return (table) annotation). Name ();
}
}
Return NULL;
}
}

 

Li xucheng csdn blog:Http://blog.csdn.net/javaeeteacher
Csdn student base camp:Http://student.csdn.net/space.php? Uid = 1, 124362
If you like myArticleAdd me as a friend:Http://student.csdn.net/invite.php? U= 124362 & C = 7be8ba2b6f3b6cc5

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.