![](/img/trans.png)
[英]Hibernate 4 Generics: @Suppress Warnings vs Infer Generic Type Arguments?
[英]Infer generic type arguments from nested generics
我想出了一個泛型函數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
以便推斷泛型類型參數?
foo
的第四個和第五個參數期望Class
es,但是您給了它IOException
和D
您可能打算給它IOException.class
和D.class
:
return foo(foo1, new C(), bar1, IOException.class, D.class);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.