如何從 Java 8 流內部拋出 CHECKED 異常? - How can I throw CHECKED exceptions from inside Java 8 streams?

問題:

How can I throw CHECKED exceptions from inside Java 8 streams/lambdas?如何從 Java 8 流/lambda 內部拋出 CHECKED 異常?

In other words, I want to make code like this compile:換句話說,我想讓這樣的代碼編譯:

public List<Class> getClasses() throws ClassNotFoundException {     

    List<Class> classes = 
        Stream.of("java.lang.Object", "java.lang.Integer", "java.lang.String")
              .map(className -> Class.forName(className))
              .collect(Collectors.toList());                  
    return classes;
    }

This code does not compile, since the Class.forName() method above throws ClassNotFoundException , which is checked.這段代碼不會編譯,因爲上面的Class.forName()方法拋出ClassNotFoundException ,它被檢查了。

Please note I do NOT want to wrap the checked exception inside a runtime exception and throw the wrapped unchecked exception instead.請注意,我不想將已檢查的異常包裝在運行時異常中,而是拋出包裝的未檢查異常。 I want to throw the checked exception itself , and without adding ugly try / catches to the stream.我想拋出已檢查的異常本身,並且不向流中添加醜陋的try / catches


解決方案:

參考一: https://stackoom.com/question/1rzYn
參考二: How can I throw CHECKED exceptions from inside Java 8 streams?
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章