transform
由于无法在通用通配符之间施加任何关系,因此无法对您的实现实施所需的约束。?
您声明中的两者SetToListTransformer
都注定各自意味着某种未知类型,无法将它们相互绑定。
正如其他人指出的那样,最简单的解决方案是SetToListTransformer
通用。例如:
class SetToListTransformer<T> implements Transformer<Set<? extends T>, List<T>> {
@Override
public List<T> transform(final Set<? extends T> input) {
final List<T> output = new ArrayList<T>(input.size());
output.addAll(input);
return output;
}
}
当然,这需要您使用特定类型参数来实例化转换器。只要SetToListTransformer
便宜,这应该没问题。但是,您表示您只想使用一个实例。以下是如何做到这一点:
class MyTransformers {
// There is no reason to expose SetToListTransformer now.
// Keep it here as an anonymous class.
private static final Transformer<Set<?>, List<?>> FROM_SET_TO_LIST =
new Transformer<Set<?>, List<?>>() {
@Override
public List<?> transform(final Set<?> input) {
return doTransform(input);
}
private <T> List<T> doTransform(final Set<T> input) {
final List<T> output = new ArrayList<T>(input.size());
output.addAll(input);
return output;
}
};
private MyTransformers() { }
public static <T> Transformer<Set<? extends T>, List<T>> fromSetToList() {
@SuppressWarnings("unchecked")//this is okay for any T because the impl is stateless
final Transformer<Set<? extends T>, List<T>> withNarrowedTypes =
(Transformer<Set<? extends T>, List<T>>)(Transformer<?, ?>)FROM_SET_TO_LIST;
return withNarrowedTypes;
}
}
这是一个使用示例:
Set<Integer> intSet = new HashSet<Integer>();
intSet.add(42);
intSet.add(1337);
List<Number> numList = MyTransformers.<Number>fromSetToList().transform(intSet);