只是給版主的。這不是一個重復的問題。
我需要一個非常棘手的問題的答案:從lambda運算式拋出例外。
我是基于這個鏈接的。https://www.baeldung.com/java-lambda-exceptions(還有很多其他的鏈接,我沒有必要在這里寫),我做了這個代碼,它是有效的。 我不得不說,只有讀過這個鏈接的人才能理解我在寫什么。
---- myMethod which throws exceptions -----
boolean myMethod(element, field, filter) {
//拋出這些的代碼。NoSuchMethodException, InvocationTargetException, IllegalAccessException。
}
---- 我的代碼中某處感興趣的母親方法-----
public <T> List<T> mamaMethod(List< T> list, String field, String filter) {
return list == null ? null :
list.stream().filter(myMehtod(element, field, filter)).collectors.toList()。
}
//這里的 "myMethod "拋出這些。NoSuchMethodException, InvocationTargetException, IllegalAccessException。
根據鏈接,我的解決方案
----- 我的 FunctionalInterface ------
@FunctionalInterface
public interface PredicateWith3Exceptions< T, E1 extends Exception, E2 extends Exception, E3 extends Exception> {
boolean test(T element) throws E1, E2, E3;
}
---- 我的封裝方法----
private < T, E1 擴展 NoSuchMethodException, E2 擴展 InvocationTargetException, E3 extends IllegalAccessException>
Predicate<T> wrapper(PredicateWith3Exceptions<T, E1, E2, E3> predicate) {
return element -> {
try {
return predicate.test(element)。
} catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) {
throw new RuntimeException(e)。
}
};
}
public <T> List<T> list mamaMethod(List< T> list, String field, String filter) {
return list == null ? null :
list.stream().filter(wrapper(
(PredicateWith3Exceptions<T, NoSuchMethodException, InvocationTargetException, IllegalAccessException>)
element -> myMehtod(element, field, filter)).collectors.toList()。
//在鏈接中沒有鑄造,但我的intelliJ只接受鑄造到PredicateWith3Exceptions。
}
上面的代碼作業得非常好。但是,我的問題是:
我怎樣才能生成PredicateWith3Exceptions,以適用于任何數量的例外。
這些例外在包裝器中被捕獲。我希望它們不被捕獲,而是在母方法上用throws陳述句重新拋出,例如:
這些例外在封裝器中被捕獲。
public <T> List<T> mamaMethod(。 .) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException
- 關于RuntimeException... 我不明白為什么我讀到的所有鏈接都把RuntimeException作為最終解決方案。其他的則是把它 具體到CheckedIOException。所有這些都是未經檢查的例外,我不明白為什么我必須讓一個例外靜音,反正它自己也會被拋出,而且會讓它死掉。 拋出的例外,而且它將殺死我的應用程式。
如果上述內容不被理解,我可以重寫這個問題。
非常感謝
uj5u.com熱心網友回復:
經過谷歌搜索,我發現:
問題1:在java中沒有辦法使通用型別的數量可變。
問題2:如果我不想在lambda運算式中嘗試捕捉,我可以在我撤銷這個母方法的地方捕捉RuntimeException例外。
問題3:我不應該拋出如此通用的例外。我可以拋出例如UncheckedIOException,或者其他我可以創建的擴展RuntimeException的unchecked例外。 雖然我個人不喜歡未檢查的例外,但在這種情況下是必須的,因為檢查的例外需要在已經拋出的地方被捕獲。它們不能在更高的層次上被拋出,而在母方法的簽名中要有thrown陳述句。 但是在這種情況下,只要母方法的最終使用者不知道這個RuntimeException,他就不可能知道他必須要捕捉它。 正如我發現的一些鏈接,這種做法是糟糕的編程實踐和代碼氣味。
如果有人對這些想法有自己的看法,可以作為答案自由添加。 我將把這個問題作為我的答案,作為一個解決方案。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/318643.html
標籤:
