我在尝试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;
....
}
问题是,它不能编译,因为我必须捕获isActive-和getNumber-Methods的可能异常。但是,即使我显式地使用如下所示的try-catch-Block,它仍然不能编译,因为我没有捕获异常。所以,要么是JDK有bug,要么是我不知道如何捕捉这些异常。
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){
}
}
....
}
我怎样才能让它工作呢?谁能给我点提示吗?
你必须在异常转义lambda之前捕获它:
s = s.filter(a -> {
try {
return a.isActive();
} catch (IOException e) {
throw new UncheckedIOException(e);
}
});
考虑到lambda不是在编写它的地方求值的,而是在JDK类中某个完全不相关的地方求值的。所以那将是被检查异常将被抛出的点,在那里它没有被声明。
你可以使用你的lambda的包装器来处理它,将检查异常转换为未检查异常:
public static <T> T uncheckCall(Callable<T> callable) {
try {
return callable.call();
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
你的例子可以写成
return s.filter(a -> uncheckCall(a::isActive))
.map(Account::getNumber)
.collect(toSet());
在我的项目中,我不带包装地处理这个问题;相反,我使用一种方法,有效地化解编译器的异常检查。不用说,这应该小心处理,项目中的每个人都必须意识到,在未声明的地方可能会出现受控异常。这是管道代码:
public static <T> T uncheckCall(Callable<T> callable) {
try {
return callable.call();
} catch (Exception e) {
sneakyThrow(e);
return null; // Unreachable but needed to satisfy compiler
}
}
public static void uncheckRun(RunnableExc r) {
try {
r.run();
} catch (Exception e) {
sneakyThrow(e);
}
}
public interface RunnableExc {
void run() throws Exception;
}
@SuppressWarnings("unchecked")
private static <T extends Throwable> void sneakyThrow(Throwable t) throws T {
throw (T) t;
}
and you can expect to get an IOException thrown in your face, even though collect does not declare it. In most, but not all real-life cases you would want to just rethrow the exception, anyway, and handle it as a generic failure. In all those cases, nothing is lost in clarity or correctness. Just beware of those other cases, where you would actually want to react to the exception on the spot. The developer will not be made aware by the compiler that there is an IOException to catch there and the compiler will in fact complain if you try to catch it because we have fooled it into believing that no such exception can be thrown.
为了正确地添加IOException(到RuntimeException)处理代码,你的方法看起来像这样:
Stream<Account> s = accounts.values().stream();
s = s.filter(a -> { try { return a.isActive(); }
catch (IOException e) { throw new RuntimeException(e); }});
Stream<String> ss = s.map(a -> { try { return a.getNumber() }
catch (IOException e) { throw new RuntimeException(e); }});
return ss.collect(Collectors.toSet());
现在的问题是,IOException必须被捕获为RuntimeException并转换回IOException——这将向上述方法添加更多代码。
为什么要使用Stream,因为它可以这样做——而且该方法会抛出IOException,所以也不需要额外的代码:
Set<String> set = new HashSet<>();
for(Account a: accounts.values()){
if(a.isActive()){
set.add(a.getNumber());
}
}
return set;
你也可以用lambdas传播你的静态疼痛,这样整个东西看起来可读:
s.filter(a -> propagate(a::isActive))
propagate在这里接收java.util.concurrent.Callable作为参数,并将调用期间捕获的任何异常转换为RuntimeException。在Guava中有一个类似的转换方法Throwables#propagate(Throwable)。
这个方法对于lambda方法链接来说是必不可少的,所以我希望有一天它会被添加到一个流行的库中,或者这种传播行为将是默认的。
public class PropagateExceptionsSample {
// a simplified version of Throwables#propagate
public static RuntimeException runtime(Throwable e) {
if (e instanceof RuntimeException) {
return (RuntimeException)e;
}
return new RuntimeException(e);
}
// this is a new one, n/a in public libs
// Callable just suits as a functional interface in JDK throwing Exception
public static <V> V propagate(Callable<V> callable){
try {
return callable.call();
} catch (Exception e) {
throw runtime(e);
}
}
public static void main(String[] args) {
class Account{
String name;
Account(String name) { this.name = name;}
public boolean isActive() throws IOException {
return name.startsWith("a");
}
}
List<Account> accounts = new ArrayList<>(Arrays.asList(new Account("andrey"), new Account("angela"), new Account("pamela")));
Stream<Account> s = accounts.stream();
s
.filter(a -> propagate(a::isActive))
.map(a -> a.name)
.forEach(System.out::println);
}
}