The Java type system supports only invariant types. So a List<String>
is not an List<Object>
. A List<String>
is not a List<Object>
as it is not valid to insert an Integer
into a List<String>
. However, there are types for which such a covariant type conversion is valid.
Given the classes A, B and Producer:
class A{}
class B{}
interface Producer<T> {
T next();
}
A cast for the covariant type Producer can be defined:
class Types{
@SuppressWarnings("unchecked")
public static <T> Producer<T> cast(Producer<? extends T> producer){
return (Producer<T>) producer;
}
}
This method supports to cast from Producer<A>
to Producer<Object>
and prevents invalid casts like Producer<A>
to Producer<B>
:
Producer<Object> valid = Types.<Object> cast(new Producer<A>());
Producer<A> invalid = Types.<A> cast(new Producer<B>()); //does not compile
My problem is that I cannot perform a cast from Producer<Producer<A>>
to Producer<Producer<Object>>
.
Producer<Producer<A>> producerOfA = new Producer<Producer<A>>();
Producer<Producer<Object>> producerOfObjects =
Types.<Producer<Object>> cast(producerOfA); //does not compile
Is there a way to persuade the Java type system to perform such a valid type conversion without warnings in user code?