【发布时间】:2019-05-08 01:59:09
【问题描述】:
我有这样的代码:
public interface Checker<A,B> extends BiFunction<CheckRequest<A>,Function<A,B>,CheckResponse<B>> { // ... }
public class CheckResponse<B> {
private B operationResponse;
//...
public void setOperationResponse(B operationResponse) {
this.operationResponse = operationResponse;
}
public B getOperationResponse() {
return operationResponse;
}
}
还有一个类似的方法:
public B execute(A req){
CheckRequest<A> chkReq = //...
chkReq.setOriginalRequest(req);
Function<A,B> op = //...
CheckResponse<B> chkRes= checker.apply(chkReq ,op)
// [...]
return chkRes.getOperationResponse();
}
我想将“op”的执行包装到一个检查器对象中,该对象将执行一些其他副作用。我还需要将“op”的输入和输出包装到适当的 CheckRequest 和 CheckResponse 中,以传递和取回额外的数据。但是,为了取回“op”的原始结果,我需要 CheckResponse 中的 getOperationResponse() 方法。听起来很简单。
上面的代码按预期工作,但如果我“内联”它就像:
return checker.apply(chkReq ,op).getOperationResponse();
我明白了
不兼容的类型:java.lang.Object 无法转换为 [actual B型]
如果方法调用是内联的,为什么不能正确推断 getOperationResponse() 的返回类型?
我正在使用 Oracle 的 OpenJDK11:
IMPLEMENTOR="甲骨文公司" IMPLEMENTOR_VERSION="18.9" JAVA_VERSION="11" JAVA_VERSION_DATE="2018-09-25"
Windows 10 上的 Intellij IDEA 2018.3 和 Maven 3.5.4。
【问题讨论】:
-
您能否提供
CheckResponse和CheckRequest类的(相关)代码?另外,您能否在此处添加代码:CheckRequest<A> chkReq = //...和此处Function<A,B> op = //...。听起来您在某处使用原始类型,导致checker.apply(chkReq, op)变为CheckResponse类型(有点相似,但与CheckResponse<Object>不完全相同)而不是CheckResponse<B>,从而导致给出的错误。 -
@KevinCruijssen 你很可能是对的,我错过了一段代码,其中我使用了一个工厂类,例如:
public Checker getChecker(OperationType operation) { switch(operation){ case getOperation: return new SecurityChecker<GetOperationRequest, GetOperationResponse>(serviceRepository); default: throw new UnsupportedOperationException("Unsopported Operation: "+operation); } }如果我正确理解你的提示,哪个返回类型太“原始”了..
标签: java generics types functional-programming java-11