Reputation: 35
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>
Upvotes: 0
Views: 56
Reputation: 3502
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 (i.e., 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.
The second call to m
doesn't not need to have the generic type specified because it is inferred from the assignment.
Upvotes: 3
Reputation: 1
in order to call you method m in chain it needs to return its on class "this". In your case is 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.
I hope that helps.
Upvotes: 0