java中输出自定义注解的实际内容
关于java自定义anootation的介绍见:http://jackyrong.iteye.com/blog/1900712
这里的一个例子,是输出一个使用了java自定义注解的实际内容的例子:
@Retention(RetentionPolicy.RUNTIME)public @interface DeveloperInfo { String date(); String name(); String title(); String version(); }
@DeveloperInfo(name = "A Random Coder", title = "King Lazy", date = "2010/10/01", version = "1.0")@SuppressWarnings("all") //this is here for a reason <img alt="java中输缘于定义注解的实际内容" src="http://reegz.co.za/wp-includes/images/smilies/icon_wink.gif"> public class ARandomClass { public void aRandomMethod() { // Some very random code... } @DeveloperInfo(name = "Joe Dirt", title = "Codename: The Cleaner", date = "2010/09/01", version = "1.0") public void doSomeRealWork() { // Some real code here... }}
public class AnnotationTest { @SuppressWarnings("unchecked") public static void main(String[] args) { // An instance of the class which uses the annotation. ARandomClass aRandomClass = new ARandomClass(); Class clazz = aRandomClass.getClass(); for (Annotation annotation : clazz.getAnnotations()) { System.out.printf("Class-level annotation of type: %1$s n", annotation.annotationType()); } try { Method[] methods = clazz.getMethods(); for (Method method : methods) { DeveloperInfo info = method.getAnnotation(DeveloperInfo.class); if (info != null) { System.out.printf("Method %1$s contains the DeveloperInfo annotation.n", method.getName()); printAnnotationInfo(info); } } } catch (Exception e) { e.printStackTrace(); } } /** * Outputs the data stored in the annotation. * * @param info */ private static void printAnnotationInfo(DeveloperInfo info) { System.out.printf("tName: %1$s, Title:%2$s, Date:%3$s, Version:%4$sn", info.name(), info.title(), info.date(), info.version()); } }