1.注解对象:
@Retention(RetentionPolicy.RUNTIME)@Target(ElementType.FIELD)public @interface UserBeanAnno { String desc() default "default desc"; String remark() default "default remark";}
2: 测试对象
public class UserBean { @UserBeanAnno(desc = "this is id descn",remark="this is id remark") public int id = 38; @UserBeanAnno(remark = "th is uname rmark") public String name = "用户名"; @UserBeanAnno(desc = "th is uage desc") public String age = "22"; }
3: 测试:
public class UserBeanTest { @Test public void test() { UserBean ub = new UserBean(); Class cls = ub.getClass(); Field[] fields = cls.getDeclaredFields(); for(Field field:fields){ UserBeanAnno anno = field.getAnnotation(UserBeanAnno.class); try { System.out.println("属性值:"+field.get(ub)); System.out.println("注解值1:"+anno.desc()); System.out.println("注解值2:"+anno.remark()); } catch (Exception e) { e.printStackTrace(); } } }}
4:控制台输出的结果:
方法值:38注解值1:this is id descn注解值2:this is id remark方法值:用户名注解值1:default desc注解值2:th is uname rmark方法值:22注解值1:th is uage desc注解值2:default remark