J2SE5.0 New Features Metadata
晁 晁 攀 Smallnest@163.com
Metadata, also called annotations in Java, annotation. Microsoft's .NET has this feature from the beginning, but its terminology attribute.
At this time, if you want to make money, you have to study it because
In future J2EE development, a wide range of uses, including declarations of EJB, injection in IOC, etc.
The IBM website has an article in detail it, a very good article.
http://www-900.ibm.com/developerWorks/cn/java/j-annotate1/
Http://www-900.ibm.com/developerWorks/cn/java/j-annotate2.shtml
I have been tested in Eclipse according to the example, but I can't get comment information. Later, compiled the Java file directly in the command line, and the run is normal. Although the current Eclipse editor can identify Java's annotation syntax, there is no generating Java class with annotated time when compiling. I have not carefully, maybe when Eclipse is compiled, add -target 5 parameters, guess.
Create a new note type, this type indicates a famous author and his email.
Package com.kuaff.jdk5; import java.lang.annotation. *; @Retendion (retorypolicy.Runtime) @Target (ElementType.Method) public @interface bookauthor {string name (); String email ();
Use this comment to add a note for our method:
package com.kuaff.jdk5; import java.lang.annotation.Annotation; public class MetadataShow {@BookAuthor (name = "Cao Xueqin", email = "caoxueqin@hongloumeng.books") public void introHongLouMeng () {System.out.println ("This is a good book");} public static void main (string [] args) {metadatashow metadata = new metadatashow (); try = metadata.getClass (). GetMethod ("Introhongloumeng" ) .getAnnotations (); for (Annotation a: annotation) {System.out.printf ( "oF:% s% n", ((BookAuthor) a) .name ()); System.out.printf ( "his Email (may have been logged out):% s% n ", (BookAuthor) a) .Email ());}} catch (securityException E) {E.PrintStackTrace ();} catch (nosuchmethodexception e) {e. PRINTSTACKTRACE ();}}} Please note that if you want to read these comments while the program is running, you need to add the declaration of the comment.
@ReTENTION (RETENTIONPOLICY.RUNTIME)
@Target (ElementType.Method) // may also be other types, such as annotations for declarations
This is a comment for comments.
Compile these two files:
Javac -Source 5 -Target 5 -D bin src / com / kuaff / jdk5 / *. java