![](/img/trans.png)
[英]Returning 500 internal error when CompleteableFuture throws exception
[英]CompleteableFuture code execution returning error
我是 CompleteableFuture 的新手,並且在使用此代碼時遇到了一些問題。 嘗試下面的代碼時,我收到錯誤:(54, 11)
java: no suitable method found for supplyAsync(as::address_1)method java.util.concurrent.CompletableFuture.<U>supplyAsync(java.util.function.Supplier<U>) is not applicable
(cannot infer type-variable(s) U
(argument mismatch; invalid method reference method address_1 in
class AsyncMain cannot be applied to given types required: java.lang.String found: no arguments
reason: actual and formal argument lists differ in length))
method java.util.concurrent.CompletableFuture.<U>supplyAsync(java.util.function.Supplier<U>,java.util.concurrent.Executor) is not applicable
(cannot infer type-variable(s) U
(actual and formal argument lists differ in length))
我看到錯誤消息告訴我為 CompletableFuture 調用的方法不正確,並且正在尋找存在的java.lang.String object
。 當我測試主要代碼以執行進程內函數時,我從System.out.println(contents.getClass())
等簡單測試中看到返回輸出確實是一個字符串。 歡迎任何見解。
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.concurrent.CompletableFuture;
public class AsyncMain {
public String process(String output) throws IOException {
URL address = new URL("https://api.publicapis.org/random?category=animal");
InputStreamReader reader = null;
try {
reader = new InputStreamReader(address.openStream());
} catch (IOException e) {
e.printStackTrace();
}
BufferedReader buffer = new BufferedReader(reader);
String contents = "";
String line = "";
while((line = buffer.readLine()) != null){
if (line.isEmpty()) {
break;
}
contents += line;
//System.out.println(contents);
}
return contents;
}
public String address_3(String msg) throws IOException {
return this.process(msg);
}
public String address_2(String msg) throws IOException {
return this.process(msg);
}
public String address_1(String msg) throws IOException {
return this.process(msg);
}
public static void main(String args[]) throws IOException {
AsyncMain as = new AsyncMain();
CompletableFuture<String> cf = new CompletableFuture<>();
cf.supplyAsync(as::address_1).thenApply(as::address_2).thenApply(as::address_3);
}
}
錯誤的原因是,在以下行中,
cf.supplyAsync(as::address_1).thenApply(as::address_2).thenApply(as::address_3);
你調用方法 as::address_1 沒有參數,但方法 address_1 實際上需要一個 String 參數,因為你已經有了,
public String address_1(String msg) 拋出 IOException { return this.process(msg);
}
你可以通過改變來解決這個問題
public String address_1(String msg) throws IOException {
return this.process(msg);
}
到
public String address_1() throws IOException {
return this.process("your_String_input");
}
但由於您不使用 String 輸出參數,您可以更改代碼
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.