如何将通用接口的类型绑定到另一个通用接口?
我正在尝试编写一个在多个层上有边界的接口。例如,请考虑以下代码:
// the bound type on U is unexpected and doesn't compile
public interface CollectionNumberWrapper<T extends Collection<U extends Number>> {
void setData(T data);
U sumOfAllNumbersInCollection()
};
public class NumberCollection implements List<AtomicInteger>{
///...implement...
};
public class StringCollection implements Collection<String>{
///...implement...
};
//This should be legal
public class NumberCollectionWrapper implements CollectionNumberWrapper<NumberCollection>{
@Override
void setData(NumberCollection data){
//...
};
@Override
AtomicInteger sumOfAllNumbersInCollection(){
//...
}
}
//This should not be legal, the type parameter should be out of bounds
public class StringCollectionWrapper implements CollectionNumberWrapper<StringCollection>{
}
Java 中的类型边界是否可能如此特定?
回答
你可以,但需要更多的工作:你必须写
public interface CollectionNumberWrapper<U extends Number, T extends Collection<U>> { ... }
...虽然对于这个特定的用例,我会T完全省略并简单地Collection<U>在任何地方使用。