duanAnnotation.java:
import java.lang.annotation.*; @Retention(RetentionPolicy.RUNTIME) @Inherited @Target({ElementType.FIELD,ElementType.METHOD}) @Documented public @interface duanAnnotation { String name() default "段小白"; int age() default 22; String hobby() default "运动跑步"; String school() default "黑龙江科技大学"; }me.java:
import java.lang.annotation.*; @Retention(RetentionPolicy.RUNTIME) @Inherited @Target({ElementType.FIELD,ElementType.METHOD}) @Documented public @interface duanAnnotation { String name() default "小白"; int age() default 22; String hobby() default "运动跑步"; String school() default "黑龙江科技大学"; }test.java:
import java.lang.reflect.Field; import java.lang.reflect.Method; public class test { public static void main(String[] args) { Field[] fields = me.class.getDeclaredFields(); Method[] methods = me.class.getMethods(); for (Field field : fields) { duanAnnotation annotation = field.getAnnotation(duanAnnotation.class); if(annotation!=null){ System.out.println("name="+annotation.name()+" "+"age="+annotation.age()+" "+"hobby="+annotation.hobby()+ " "+"school="+annotation.school()); } } for (Method method : methods) { duanAnnotation annotation = method.getAnnotation(duanAnnotation.class); if(annotation!=null){ System.out.println("introduce:"+annotation.name()); } } } }
编译后结果: