我希望编写对 JS 友好的 async/await 代码,但是,我的类继承似乎不起作用:
import java.util.concurrent.CompletableFuture;
class Main {
public static class Promise<T> extends CompletableFuture<T>{}
public static void main(String[] args) {
System.out.println(System.getProperty("java.version"));
// This works:
CompletableFuture<String> p1 = Promise.supplyAsync(()->{
return "foobar";
});
// This doesn't, but i need this:
Promise<String> p2 = Promise.supplyAsync(()->{
return "foobar";
});
}
}
棘手的部分是我需要返回为
Promise<T>
而不是 CompletableFuture<T>
,制作一个 JS 友好的实用程序。
错误:
ERROR!
/tmp/kpS1aJoUkj/Main.java:13: error: incompatible types: no instance(s) of type variable(s) U exist so that CompletableFuture<U> conforms to Promise<String>
Promise<String> p2 = Promise.supplyAsync(()->{
^
where U is a type-variable:
U extends Object declared in method <U>supplyAsync(Supplier<U>)
1 error
如果在 p2 的右侧添加了强制类型转换,则错误为:
ERROR!
Exception in thread "main" java.lang.ClassCastException: class java.util.concurrent.CompletableFuture cannot be cast to class Main$Promise (java.util.concurrent.CompletableFuture is in module java.base of loader 'bootstrap'; Main$Promise is in unnamed module of loader 'app')
at Main.main(Main.java:13)
测试于 https://www.programiz.com/java-programming/online-compiler/
您收到的错误是因为
supplyAsync()
返回 CompletableFuture
并且您试图将其分配给 Promise
。作业无法正确编译,因为 CompletableFuture
不是 Promise
。
您可以通过编写可从
Promise
构造的 CompletableFuture
类来解决此问题 - 也许可以通过将 CompletableFuture
保存在私有字段中并将其方法委托给它。