自定义注解:
@Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) @interface Mark { String author() default "zhang"; String comments(); }
使用 @interface 定义注解,Target 是注解使用的目标,Retention 是注解的生存期。
使用注解:
class MarkExample { @Mark(author = "zhang", comments = "test") private void sayHello() { System.out.println("hello"); } }
解析注解:
public static void main(String[] args) { MarkExample example = new MarkExample(); // Method[] methods = example.getClass().getMethods(); // 获得 MarkExample 类声明的方法 Method[] methods = example.getClass().getDeclaredMethods(); for (Method m : methods) { if (m.isAnnotationPresent(Mark.class)) { try { // 遍历方法上的注解 for (Annotation annot : m.getDeclaredAnnotations()) { System.out.println(annot); } // 获取 Mark 注解,得到属性值 Mark mark = m.getAnnotation(Mark.class); System.out.println(mark.author()); } catch (Throwable ex) { ex.printStackTrace(); } } } }
浙公网安备 33010602011771号