【发布时间】:2018-08-08 19:45:09
【问题描述】:
我有这个代码
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
如何解决?
【问题讨论】:
-
你需要在 lambda 函数的主体中捕获它。
-
请教我怎么做...
-
你的逻辑有缺陷。
getMethod()永远不会返回 null。 -
请注意,getMethod 永远不会返回 null,所有 JComponent 都有一个 setFont() 方法,因为它是在 JComponent 中声明的,NullPointerException 永远不应被捕获,并且 catch 块永远不应为空:这只是隐藏了错误并使它们很难诊断。这段代码没有意义。
-
@JBNizet 我花了一段时间才意识到这段代码实际上是在调用
setFont方法,而.forEach(m -> m.setFont(someFont))中没有反射,这使得整个filter步骤更加荒谬,因为编译器已经声明setFont方法始终存在于所有流元素中……
标签: java reflection lambda java-stream