我在尝试Java 8的Lambda表达式时遇到了问题.通常它工作正常,但现在我有方法可以抛出IOException.最好看一下以下代码:
class Bank{
....
public Set<String> getActiveAccountNumbers() throws IOException {
Stream<Account> s = accounts.values().stream();
s = s.filter(a -> a.isActive());
Stream<String> ss = s.map(a -> a.getNumber());
return ss.collect(Collectors.toSet());
}
....
}
interface Account{
....
boolean isActive() throws IOException;
String getNumber() throws IOException;
....
}
Run Code Online (Sandbox Code Playgroud)
问题是,它不能编译,因为我必须捕获isActive-和getNumber-Methods的可能例外.但即使我明确使用如下所示的try-catch-Block,它仍然无法编译,因为我没有捕获异常.所以要么JDK中存在错误,要么我不知道如何捕获这些异常.
class Bank{
....
//Doesn't compile either
public Set<String> getActiveAccountNumbers() throws IOException {
try{
Stream<Account> s = accounts.values().stream();
s = s.filter(a -> a.isActive());
Stream<String> ss = s.map(a -> a.getNumber());
return ss.collect(Collectors.toSet());
}catch(IOException ex){
} …Run Code Online (Sandbox Code Playgroud) 我正在使用Eclipse Luna Service Release 2(4.4.2),Java 8 u51.
我正在尝试创建一个方法,该方法将基于另一个方法参数创建传递对象的实例.原型简化为
public <T> T test(Object param, T instance) {
Constructor<?> constructor = instance.getClass().getConstructors()[0]; // I actually choose a proper constructor
// eclipse reports "Unhandled exception type InvocationTargetException"
Function<Object, Object> createFun = constructor::newInstance;
T result = (T) createFun.apply(param);
return result;
}
Run Code Online (Sandbox Code Playgroud)
在线Function声明eclipse报告Unhandled exception type InvocationTargetException编译器错误.我需要Function稍后在流中使用.
我试图添加各种try/catch块,抛出声明,但没有修复此编译器错误.
如何使这段代码工作?