[英]Type inference issue for generic method
Is it possible to resolve the problem with weak inference without defining additional variables or type casts for code below? 是否可以在不为下面的代码定义其他变量或类型强制转换的情况下,以弱推断来解决问题?
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>
Yes: 是:
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);
We need to fix the fact that cl
might be an erased type (ie, a super type of the generic type, R
), and then we need to tell the compiler what the real type R
is since the method argument is only indicating the super type. 我们需要解决以下事实:
cl
可能是已擦除类型(即,通用类型R
的超类型),然后我们需要告诉编译器实际类型R
是什么,因为method参数仅指示超级类型。类型。
The second call to m
doesn't not need to have the generic type specified because it is inferred from the assignment. 对
m
的第二次调用不需要指定泛型,因为它是从赋值中推断出来的。
in order to call you method m in chain it needs to return its on class "this". 为了在链中调用您的方法m,它需要在类“ this”上返回它。 In your case is GenericClass.
您的情况是GenericClass。 This should work.
这应该工作。
class GenericClass<T> {
public <R> GenericClass<T> m(Class<R> cl) {
// code to do something here
return this;
}
}
for every call to the "m" method it will return it's own class then you can call it again. 每次对“ m”方法的调用都会返回它自己的类,然后您可以再次调用它。
I hope that helps. 希望对您有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.