Java 来自接口的适配器<;类型>;接口<;亚型>;

Java 来自接口的适配器<;类型>;接口<;亚型>;,java,generics,casting,wrapper,Java,Generics,Casting,Wrapper,考虑以下接口 public interface Feed<T> { public void put( T o ); } 假设有一种方法writeSubsTo(feedf),我们有一个cf的实例CollectionFiller。由于cf只将对象添加到其“super”集合中,因此可以安全地将其传递到writeSubsTo。但是编译器不允许这样做。(我很清楚这种行为的原因。) 我想编写一个方便的适配器,它围绕X类型的CollectionFiller,充当X类型特定子类型的Fe

考虑以下接口

public interface Feed<T> {

    public void put( T o );

}
假设有一种方法
writeSubsTo(feedf)
,我们有一个
cf
的实例
CollectionFiller
。由于
cf
只将对象添加到其“super”集合中,因此可以安全地将其传递到
writeSubsTo
。但是编译器不允许这样做。(我很清楚这种行为的原因。)

我想编写一个方便的适配器,它围绕X类型的
CollectionFiller
,充当X类型特定子类型的
Feed

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 );
    }

}
类子填充器实现提要{
私人最终收集填料收集填料;
副加注口(收集加注口收集加注口){
this.collectionFiller=collectionFiller;
}
公众认沽期权(T2 o){
此.collectionFiller.put(o);
}
的公共静态子填充器(CollectionFiller c){
返回新的子加注器(c);
}
}
虽然这个类没有什么问题,但编译器不会接受下面代码段中的最后两个语句

CollectionFiller<Super> cf = CollectionFiller.of( new HashSet<Super>() );
SubFiller<Super, Sub> sf = SubFiller.of( cf );
writeSubsTo( SubFiller.of( cf ) );
CollectionFiller cf=CollectionFiller.of(new HashSet());
次填充器sf=次填充器of(cf);
(cf)的子填入器;

有人能想出一个解决这个问题的好办法吗?我不介意适配器是否包含繁琐的代码,只要使用它不太冗长(因此使用静态工厂方法)。当然,任何其他解决方案(不使用适配器)也可以(同样,只要使用它不太冗长)。

如果您使用
writeSubsTo(提要)
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 );
    }

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