是否可以将下面给定的for循环转换为Java 8代码?
Object[] args = pjp.getArgs();
MethodSignature methodSignature = (MethodSignature) pjp.getStaticPart()
.getSignature();
Method method = methodSignature.getMethod();
Annotation[][] parameterAnnotations = method.getParameterAnnotations();
StringBuilder methodArgs = new StringBuilder();
for (int argIndex = 0; argIndex < args.length; argIndex++) {
for (Annotation annotation : parameterAnnotations[argIndex]) {
if ((annotation instanceof RequestParam) || (annotation instanceof PathVariable) || (annotation instanceof RequestHeader)) {
methodArgs.append(args[argIndex] + "|");
} else if ((annotation instanceof RequestBody)) {
methodArgs.append(mapper.writeValueAsString(args[argIndex]) + "|");
}
}
}
我尝试使用下面给出的Java 8代码。函数名称是随机获取的
public void some() {
Annotation[][] parameterAnnotations = method.getParameterAnnotations();
Arrays.stream(parameterAnnotations)
.map(f -> asd(f));
}
private Object asd(Annotation[] annotations) {
Arrays.stream(annotations)
.map(a -> change(a)); //here is problem...how i can access args[argIndex]
return null;
}
答案 0 :(得分:1)
您必须打开一个InsStream
以遍历args
索引,然后为每个SimpleEntry
创建一个arg
,并与之对应的annotaton
(根据您的代码),然后您可以应用业务逻辑。
IntStream.range(0, args.length)
.mapToObj(argIndex -> new AbstractMap.SimpleEntry<>(args[argIndex], parameterAnnotations[argIndex]))
.flatMap(objectSimpleEntry -> Arrays.stream(objectSimpleEntry.getValue()).map(annotation -> new AbstractMap.SimpleEntry<>(objectSimpleEntry.getKey(), annotation)))
.forEach(objectAnnotationSimpleEntry -> {
Annotation annotation = objectAnnotationSimpleEntry.getValue();
Object arg = objectAnnotationSimpleEntry.getKey();
if ((annotation instanceof RequestParam) || (annotation instanceof PathVariable) || (annotation instanceof RequestHeader)) {
methodArgs.append(arg + "|");
} else if ((annotation instanceof RequestBody)) {
methodArgs.append(arg + "|");
}
});