jdk1.8的java.lang.Class
类新增了方法getAnnotationsByType
方法,该方法可以获取某一个类型的注解列表,具体代码示例如下:
public class AnnotationTest {
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface Filters {
Filter[] value();
}
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Repeatable(Filters.class)
public @interface Filter {
String value();
}
@Filter("filter1")
@Filter("filter2")
public interface Filterable {
}
@Filters({@Filter("filter1"), @Filter("filter2")})
public interface Filterable2 {
}
public static void main(String[] args) {
for (Filter filter : Filterable.class.getAnnotationsByType(Filter.class)) {
System.out.println(filter.value());
}
for (Filters filter : Filterable.class.getAnnotationsByType(Filters.class)) {
System.out.println(filter.value().length);
}
for (Filter filter : Filterable2.class.getAnnotationsByType(Filter.class)) {
System.out.println(filter.value());
}
for (Filters filter : Filterable2.class.getAnnotationsByType(Filters.class)){
System.out.println(filter.value().length);
}
}
}
输出如下:
filter1
filter2
2
filter1
filter2
2
上面可以看出getOrDefault
第二个参数的类型可以通过第一个参数来推断,如果在jdk1.8之前,需要写成如下形式:
value.getOrDefault("asas", Value.<String>defaultValue());