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