[英]Type inference issue for generic method
是否可以在不為下面的代碼定義其他變量或類型強制轉換的情況下,以弱推斷來解決問題?
public class GenericClass<T> {
public <R> R m(Class<R> cl) {
return null;
}
}
GenericClass<SomeClass> v2 = new GenericClass<SomeClass>()
.m(GenericClass.class)
.m(GenericClass.class); // <- Object cannot be converted to GenericClass<SomeClass>
是:
public class GenericClass<T> {
public <R> R m(Class<? super R> cl) {
return null;
}
}
GenericClass<SomeClass> v2 = new GenericClass<SomeClass>()
.<GenericClass<SomeClass>>m(GenericClass.class)
.m(GenericClass.class);
我們需要解決以下事實: cl
可能是已擦除類型(即,通用類型R
的超類型),然后我們需要告訴編譯器實際類型R
是什么,因為method參數僅指示超級類型。類型。
對m
的第二次調用不需要指定泛型,因為它是從賦值中推斷出來的。
為了在鏈中調用您的方法m,它需要在類“ this”上返回它。 您的情況是GenericClass。 這應該工作。
class GenericClass<T> {
public <R> GenericClass<T> m(Class<R> cl) {
// code to do something here
return this;
}
}
每次對“ m”方法的調用都會返回它自己的類,然后您可以再次調用它。
希望對您有所幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.