Support covariant type conversion in Java

The Java type system only supports immutable types So list < string > is not list < Object > The list < string > is not a list < Object > because inserting an integer into the list < string > is not valid However, there is a valid type for this covariant type conversion

Whereas a, B and producer categories:

class A{}
class B{}
interface Producer<T> {
    T next();
}

You can define the cast of covariant type producer:

class Types{
    @SuppressWarnings("unchecked")
    public static <T> Producer<T> cast(Producer<? extends T> producer){
        return (Producer<T>) producer;
    }
}

This method supports cast from producer < a > Producer < Object > and prevent invalid cast producers like producer < a > 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 can't execute cast producer < producer < Object > > from producer < producer < a > >

Producer<Producer<A>> producerOfA = new Producer<Producer<A>>();
Producer<Producer<Object>> producerOfObjects = 
   Types.<Producer<Object>> cast(producerOfA); //does not compile

Is there any way to persuade the Java type system to perform this effective type conversion without warning in user code?

Solution

You haven't released the code of producer yet, but it should be covariant according to the name and assertion. Maybe anywhere you say now:

Producer<Foo>

You should say:

Producer<? extends Foo>

It would be nice if Java would automatically realize that the generic interface is equivalent to its generic form (for example, iterator and iteratable are also security covariant), but at least for now, it won't

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>