Java 8,流过滤器,反射,NoSuchMethodException [重复]

问题描述 投票:3回答:1

这个问题在这里已有答案:

我有这个代码

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

怎么解决这个?

java reflection lambda java-stream
1个回答
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并停止处理。

© www.soinside.com 2019 - 2024. All rights reserved.