我想在 Java 8 中创建新代码后解决 Sonar 问题。
public class Argument<T> {
...
public T getValue() {
return parameterType.transform(group.getValues());
}
...
}
我的代码:
List<Argument<?>> args = expression.match(text);
return args == null ? null : args.stream().map(arg -> arg.getValue()).collect(Collectors.toList());
Sonar 说:
Lambda 应该替换为方法引用。方法/构造函数引用比使用 lambda 更紧凑、更易读,因此是首选。同样,空检查可以替换为对 Objects::isNull 和 Objects::nonNull 方法的引用。
我想将 map(arg -> arg.getValue())
更改为 map(T::getValue())
但编译错误吗 ().
最佳答案
Lambdas should be replaced with method references
改变
.map(arg -> arg.getValue())
至
.map(Argument::getValue)
至于:
Similarly, null checks can be replaced with references to the Objects::isNull and Objects::nonNull methods
我以前没有使用过 Sonar,但如果它更喜欢使用 Objects.isNull
和 Objects.nonNull
进行 null 检查,那么您需要执行以下操作:
return Objects.isNull(args) ? null : args.stream()
.map(Argument::getValue)
.collect(Collectors.toList());
关于java - 通用类型的流图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58141765/