【发布时间】:2019-07-25 05:17:35
【问题描述】:
我想出了一个泛型函数foo,它链接两个泛型函数,同时捕获泛型异常并返回泛型。但是我不能调用它。这里的类型和参数可能有点令人困惑,但在这里使用更详细的名称同样令人困惑。
函数 bar 应该提供所有泛型类型来推断它们,但它显示编译错误,我也无法显式添加它们(execute<E, Class<D>, D, IOException>(...) 导致“不适用于参数”)。
我已经尝试了几个小时,并且使用fooBar 编译没有问题。所以我想类型兼容性没有问题,而是我如何在bar 中调用foo 或如何推断它们。
public class A {
// similiar to BiFunction but throws Exception
static interface Foo<P1, P2, R> { R apply(P1 p1, P2 p2) throws Exception; }
static class Bar extends RuntimeException { /*...*/ }
public static <R1, D1, R2, E1 extends Exception> R2 foo(Foo<B, C, R1> arg1, C arg2, BiFunction<R1, Class<D1>, R2> arg3, Class<E1> arg4, Class<D1> arg5) {
try {
B b1 = new B();
R1 r1 = arg1.apply(b1, arg2);
return arg3.apply(r1, arg5);
} catch (Exception e1) {
if (arg4.isInstance(e1)) {
return null;
}
throw new Bar();
}
}
public static D bar() {
Foo<B, C, E> foo1 = (b1, c1) -> b1.foo(c1); // where B.foo(C) returns E
BiFunction<E, Class<D>, D> bar1 = (e1, cClass) -> e1.bar(cClass); // where E.bar(Class<D>) returns D
return foo(foo1, new C(), bar1, new IOException(), new D()); // compile error: cannot infer generic type arguments
}
public static D fooBar() {
Foo<B, C, E> foo1 = (b1, c1) -> b1.foo(c1); // where B.foo(C) returns E
BiFunction<E, Class<D>, D> bar1 = (e1, cClass) -> e1.bar(cClass); // where E.bar(Class<D>) returns D
try {
B b1 = new B();
E e1 = foo1.apply(b1, new C());
return bar1.apply(e1, D.class);
} catch (Exception e1) {
if (IOException.class.isInstance(e1)) {
return null;
}
throw new Bar();
}
}
}
粘贴和格式化花费了无限长的时间,如果我输入错误,我很抱歉。 如何调用foo以便推断出泛型类型参数?
【问题讨论】:
-
我认为你应该花点时间确保这段代码没有小错误,例如第一个方法没有返回类型。
-
@michalk 对,我在打字时错过了
R2,谢谢。
标签: java generics compiler-errors type-inference