【发布时间】:2019-07-22 13:29:02
【问题描述】:
我有一个javaSDK,它使用OkHttp客户端(4.0.0)从IAM服务器获取令牌并将令牌返回给应用程序。关系可能是这样的:Applicaiton同步调用SDK,SDK异步调用IAM。参考这个答案Java - Retrieving Result from OkHttp Asynchronous GET,代码如下:
异步类:
class BaseAsyncResult<T> {
private final CompletableFuture<T> future = new CompletableFuture<>();
T getResult() {
try {
return future.get();
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
return null;
}
void onFailure(IOException e) {
future.completeExceptionally(e);
}
void onResponse(Response response) throws IOException {
String bodyString = Objects.requireNonNull(response.body()).string();
future.complete(IasClientJsonUtil.json2Pojo(bodyString, new TypeReference<T>() {}));
}
}
Okhttp 调用如下:
public void invoke(Request request, BaseAsyncResult result) {
okHttpClient.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(@NotNull Call call, @NotNull IOException e) {
result.onFailure(e);
}
@Override
public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
result.onResponse(response);
}
});
}
应用程序使用 sdk 代码,iasClient 是 okhttp 客户端的包装器:
BaseAsyncResult<AuthenticationResponse> iasAsyncResult = new BaseAsyncResult();
iasClient.invoke(request, iasAsyncResult);
AuthenticationResponse result = iasAsyncResult.getResult();
错误信息:
java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to x.x.x.AuthenticationResponse
我错过了什么?
【问题讨论】:
-
@Arpan Kanthal 的一个方法是向 BaseAsyncResult 添加一个私有 Class
类型变量,然后在 json2Pojo 函数中使用该类,然后 BaseAsyncResult 可能如下所示: