开发者

Adapter from Interface<Type> to Interface<Subtype>

开发者 https://www.devze.com 2023-04-04 18:21 出处:网络
Consider the following interface. public interface Feed<T> { public void put( T o ); } We have a straightforward Java class implementing this interface, that writes objects to a specific co

Consider the following interface.

public interface Feed<T> {

    public void put( T o );

}

We have a straightforward Java class implementing this interface, that writes objects to a specific collection.

public class CollectionFiller<T> implements Feed<T> {

    private final Collection<T> collection;

    private CollectionFiller( Collection<T> collection ) {
        this.collection = collection;
    }

    public void put( T o ) {
        this.collection.add( o );
    }

    public static <T> CollectionFiller<T> of( Collection<T> collection ) {
        return new CollectionFiller<T>( collection );
    }

}

Now we define two dummy classes, in order to make the question concrete.

public class Super {}

public class Sub extends Super {}

Let's say there is some method writeSubsTo( Feed<Sub> f ) and we have an instance cf of CollectionFiller<Super>. Since cf only adds objects to its collection of "Supers", it would be safe to pass it to writeSubsTo. The compiler won't allow it however. (The reason for this behavior is clear to me.)

I wanted to write a convenience adapter that wraps around a CollectionFiller of type X and poses as a Feed of a specific subtype of type X. I tried (among many other things) the following, but the compiler gives me trouble.

class SubFiller<T1, T2 extends T1> implements Feed<T2> {

    private final CollectionFiller<T1> collectionFiller;

    SubFiller( CollectionFiller<T1> collectionFiller ) {
        this.collectionFiller = collectionFiller;
    }

    public void put( T2 o ) {
        this.collectionFiller.put( o );
    }

    public static 开发者_运维百科<T1, T2 extends T1> SubFiller<T1, T2> of( CollectionFiller<T1> c ) {
        return new SubFiller<T1, T2>( c );
    }

}

Although there is nothing wrong with this class, the compiler won't accept both of the last two statments in the following code fragment.

CollectionFiller<Super> cf = CollectionFiller.of( new HashSet<Super>() );
SubFiller<Super, Sub> sf = SubFiller.of( cf );
writeSubsTo( SubFiller.of( cf ) );

Can anyone think of a nice way of solving this problem? I wouldn't mind if the adapter contained cumbersome code, as long as using it is not too verbose (hence the static factory methods). Of course, any other solution (not using an adapter) is also fine (again, as long as using it isn't too verbose).


If you use writeSubsTo(Feed<? super Sub> f), then you can pass in a Feed<Super>. Then you can do away with your filler classes altogether. Yay for contravariance! :-P

(There's also a covariant version, ? extends X, for cases where you're getting values out rather than putting values in.)

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号