首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

java中输缘于定义注解的实际内容

2013-07-09 
java中输出自定义注解的实际内容关于java自定义anootation的介绍见:http://jackyrong.iteye.com/blog/1900

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()); } }

热点排行