Java 8,流过滤器,反射,NoSuchMethodException

时间:2018-02-28 20:18:52

标签: java reflection lambda java-stream

我有这段代码

List<JComponent> myList = new ArrayList<>();
fillmyList(myList); //Some method filling the list
try{
    menuList.stream()
    .filter(m->m.getClass().getMethod("setFont", new Class[]{Font.class}) != null) //unreported exception NoSuchMethodException; must be caught or declared to be thrown
    .forEach(m -> m.setFont(someFont));
}
catch (NullPointerException |  NoSuchMethodException e) {} //exception NoSuchMethodException is never thrown in body of corresponding try statement

但是,我有这个错误消息:

Exception in thread "AWT-EventQueue-0" java.lang.RuntimeException: Uncompilable source code - exception java.lang.NoSuchMethodException is never thrown in body of corresponding try statement

如何解决这个问题?

1 个答案:

答案 0 :(得分:3)

这不是例外,而是编译错误 你必须捕获可能抛出异常的lambda体,而不是整个流。

以下是在false中为已抛出异常的流的元素返回filter()的示例:

myList.stream()
      .filter(m -> {
          try {
              return m.getClass()
                      .getMethod("setFont", new Class[] { Font.class }) != null;
          } catch (NoSuchMethodException | SecurityException e) {
              // log the exception
              return false;
          }
      })

您当然可以使用不同的策略来抛出RuntimeException并停止处理。