我java7代码:
final Map<String, Method> result = new HashMap<>();
final Set<Class<?>> classes = getClasses(co.glue());
for (final Class<?> c : classes) {
final Method[] methods = c.getDeclaredMethods();
for (final Method method : methods) {
for (final Annotation stepAnnotation : method.getAnnotations()) {
if (stepAnnotation.annotationType().isAnnotationPresent(StepDefAnnotation.class)) {
result.put(stepAnnotation.toString(), method);
}
}
}
}
return result;
我尝试用stream
+ flatMap
+ map
+ filter
result = classes.stream()
.flatMap(c-> c.getDeclaredMethods()
.stream())
.map(Annotation::getAnnotations)
.filter(...?????);
分析解答
你可以用stream
和flatMap
喜欢这样做:
return classes.stream()
.flatMap(c -> Arrays.stream(c.getDeclaredMethods()))
.flatMap(m -> Arrays.stream(m.getAnnotations())
.filter(stepAnnotation -> stepAnnotation.annotationType().isAnnotationPresent(StepDefAnnotation.class))
.map(ann -> new AbstractMap.SimpleEntry<>(ann.toString(), m)))
.collect(Collectors.toMap(AbstractMap.SimpleEntry::getKey, AbstractMap.SimpleEntry::getValue));