modern-java-zh icon indicating copy to clipboard operation
modern-java-zh copied to clipboard

Annotation部分 确认有误

Open Jijun opened this issue 7 years ago • 0 comments

@interface Hints { Hint[] value(); }

@Repeatable(Hints.class) @interface Hint { String value(); } @Hint("hint1") @Hint("hint2") class Person { }

Hint hint = Person.class.getAnnotation(Hint.class); System.out.println(hint); // null

Hints hints1 = Person.class.getAnnotation(Hints.class); System.out.println(hints1.value().length); // 2 这块有错误,使用java8运行空指针异常

Hint[] hints2 = Person.class.getAnnotationsByType(Hint.class); System.out.println(hints2.length); // 2

需要将代码的annotation的加上@Retention(RetentionPolicy.RUNTIME),否则默认是@Retention(RetentionPolicy.CLASS),不过源代码是有这个策略的,但是文档没有所以为了避免误导开发者,尽量加上这块

原文也有一个issue https://github.com/winterbe/java8-tutorial/issues/36

Jijun avatar Mar 26 '18 06:03 Jijun