新建一个注释类型,这个类型指明了一本名著的作者和他的email。

java 代码import java.lang.annotation.*; @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public@interface BookAuthor { String name(); String email(); }


使用这个注释为我们的方法加上注解:

java 代码import java.lang.annotation.Annotation; publicclass MetadataShow { @BookAuthor(name='曹雪芹',email='caoxueqin@hongloumeng.books') publicvoid introHongLouMeng() { System.out.println('这是一本好书啊'); } publicstaticvoid main(String[] args) { MetadataShow metadata = new MetadataShow(); try { Annotation[] annotation = metadata.getClass().getMethod('introHongLouMeng').getAnnotations(); for(Annotation a : annotation) { System.out.printf('作者:%s%n', ((BookAuthor)a).name()); System.out.printf('他的电子邮件(可能已被注销):%s%n', ((BookAuthor)a).email()); } } catch (SecurityException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); } } }

请注意,要想在程序运行时能读取这些注释,需要在注释的声明的时候加上

@Retention(RetentionPolicy.RUNTIME)

@Target(ElementType.METHOD) //也可能时其他类型,如针对声明的注释

这是对注释的注释。

编译这两个文件:

javac -source 5 -target 5 -d bin src/com/kuaff/jdk5/*.java

[@more@]