簡體   English   中英

是否有一個標准的Java 8 FunctionalInterface用於拋出已檢查異常的塊?

[英]Is there a standard Java 8 FunctionalInterface for a block throwing a checked exception?

可調用拋出異常,Runnable沒有。

有什么標准看起來像

@FunctionalInterface
public interface TypedBlock<E extends Exception> {
    public void run() throws E;
}

不,我知道沒有內置功能。 但是您可以使用外部庫(以及許多其他很酷的功能)。

您可以使用JOOL ,您可以在其中使用Unchecked類。

該頁面的示例使用IOException演示了這一點

Arrays.stream(dir.listFiles()).forEach(
    Unchecked.consumer(file -> { System.out.println(file.getCanonicalPath()); })
);

另一種(在我看來更好)的方法是使用功能設計的庫,如Functionaljava

如果結果成功,一個好的方法是將您的任務包裝在Validation以便隨后決定。 這看起來像這樣:

TypedBlock<IOException> foo = ...;

// do your work
final Validation<IOException, Unit> validation = Try.f(() -> {
  foo.run();
  return Unit.unit(); // Unit equals nothing in functional languages
})._1();

// check if we got a failure
if (validation.isFail()) {
  System.err.println("Got err " + validation.fail());
}

// check for success
if (validation.isSuccess()) {
  System.out.println("All was good :-)");
}

// this will just print out a message if we got no error
validation.forEach(unit -> System.out.println("All was good"));

java.lang.AutoCloseable有一個()->{} throws Exception簽名,然而,它是預定義語義的負擔。 因此,對於臨時使用它可能是合適的,但是當您設計API時,我建議您定義自己的interface

請注意,您的專用接口仍然可以將Callable<Void>擴展為標准interface

interface Block<E extends Exception> extends Callable<Void>{
    void run() throws E;
    @Override default Void call() throws E { run(); return null; }
    /** This little helper method avoids type casts when a Callable is expected */
    static <T extends Exception> Block<T> make(Block<T> b) { return b; }
}

這樣,您可以將Block接口與現有API一起使用:

// Example
ExecutorService e=Executors.newSingleThreadExecutor();
try {
    e.submit(Block.make(()->{ throw new IOException("test"); })).get();
} catch (InterruptedException ex) {
    throw new AssertionError(ex);
} catch (ExecutionException ex) {
    System.out.println("received \""+ex.getCause().getMessage()+'"');
}
e.shutdown();

請注意靜態方法Block.make 如果沒有它,您必須將lambda表達式轉換為(Block<IOException>)而不是從改進的類型推斷中獲利。 只有在需要Callable情況下才需要這個,對於你自己的需要Block的API,你可以直接使用lambda表達式和方法引用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM