![](/img/trans.png)
[英]Java8: How to get the internal Type of java.util.Optional class?
[英]Is there a java8 standard library class that means “possibly with exception” in the same way as java.util.Optional means “possibly null”?
我有一個名為CalculationOutcome
和FileHashOutcome
課程。 他們的構造函數有(ActualResult, Throwable)
參數,並且在CompletionStage
鏈的末尾我有handle(XxxOutcome::new)
。
如果我可以寫出PossiblyWithError<FileHash>
它可能會使意圖更清晰並保存一些樣板。
編輯:人們要求代碼示例...
class FileHashOutcome {
private final String hash;
private final Throwable throwable;
FileHashOutcome(String hash, Throwable throwable){
// Usual assignments
}
}
CompletionStage<FileHashOutcome> future =
SomeExternalLibrary.calculateHash(file)
// ...It's a CompletionStage<String> at this stage...
.handle(FileHashOutcome::new);
// Then I pass `future` to a service that
// will execute it and pass back the result asynchronously
具體而言,它是一個阿卡演員中,和我要求的基礎設施, 管結果回到演員的消息。
編輯: CompletableFuture
可以完成工作的建議......是的,好的,它代表了需要表達的內容。 而實現你自己的粗糙和未來的未來,然后將它包裝在java8的未來,這有點代碼味道。
根據您是否可以訪問未來的“信封”,可以跳過一些環節。 如果你在thenApply
那么你就在信封的“內部”而你卻不知道。 並且Akka基礎設施“拋棄”信封並且僅返回結果(如果存在異常則它不返回任何內容,這是我想要在CompletionStage
鏈的末尾捕獲並包裝該異常的主要原因之一) 。 當然,自從我創建了CompletionStage之后,我可以在成員變量中保留它,直到基礎結構讓我覺得它已經完成。
根據@marstran,這個類的通常名稱是Try 。
Scala在其標准庫中有這樣一個類: https : //www.scala-lang.org/api/2.9.3/scala/util/Try.html
同樣可以在Java中完成,但它不是標准庫的一部分: https : //dzone.com/articles/why-try-better-exception-handling-in-java-with-try
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.