自定义注解
自定义注解: public @interface Description{//使用@interface关键字注解 元注解 下面以一个demo演示解析注解 package com.description.demo; import java.lang.annotation.Documented; java.lang.annotation.ElementType; java.lang.annotation.Inherited; java.lang.annotation.Retention; java.lang.annotation.RetentionPolicy; java.lang.annotation.Target; //注解的作用域 @Target({ElementType.METHOD,ElementType.TYPE}) 注解的生命周期 @Retention(RetentionPolicy.RUNTIME) 注解是否允许被继承 @Inherited 是否生成注解Javadoc文档子注解 @Documented public @interface Description { String desc(); String auth()default"rongrong"; } 接口 public Person { String name(); int age(); void say(); } 实现类 com.description.demo; @Description(desc = "class annotation") class Child implements Person { @Override @Description(desc = "method annotation") public String name() { TODO Auto-generated method stub return null; } @Override age() { return 0 say() { TODO Auto-generated method stub } } 测试类: /** * */ java.lang.annotation.Annotation; java.lang.reflect.Method; org.junit.Test; * @author Administrator * 解析注解 class MainTest { @SuppressWarnings("unchecked") @Test run(){ try { 通过反射加载实体类 Class c = Class.forName("com.description.demo.Child"); 找到类上面的注解 boolean isExist= c.isAnnotationPresent(Description.); if (isExist) { 拿到实体类,一定强转为注解类型,反则找不到 Description d = (Description) c.getAnnotation(Description.); System.out.println(d.desc()); } 找到方法上的注解 Method[] method = c.getMethods(); for (Method ms : method) { isExist = ms.isAnnotationPresent(Description.); (isExist) { Description d = ms.getAnnotation(Description.); System.out.println(d.desc()); } 另一种方法 Annotation[] annotation = ms.getAnnotations(); (Annotation as : annotation) { if (as instanceof Description) { String desc = ((Description) as).desc(); System.out.println(desc); } } } } catch (ClassNotFoundException e) { TODO Auto-generated catch block e.printStackTrace(); } } } ? (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |