这里的问题是抛出异常的是lambda,并且forEach中使用的lambda没有被声明为抛出异常.请参见
Consumer文档.
解决这个问题的最佳方法是使用老式的for-each循环:
for (Method method : methods) {
method.invoke(instance);
}
虽然可以使用这样的东西:
methods.forEach(method -> {
try {
method.invoke(instance);
} catch (IllegalAccessException | InvocationTargetException e) {
throw new RuntimeException(e);
}
});
在我看来它并没有真正帮助你,因为你不能再从lambda中抛出完全相同的异常,你必须将它包装在RuntimeException中,这不是很好……
IntelliJ cannot correct it either. In intention actions if I select Add Exceptions to Method Signature, it does nothing.
IntelliJ无法做到这一点的原因是因为它是Consumer接口的一部分,它是JDK的一部分. IntelliJ没有办法修改它.当然,IntelliJ可以更好地处理这个问题.
结论:
有时候lambdas是有用的,有时旧的做事方式更好.