我已经搜索了一下,目前还没有找到在Java中同时对通配符类型设置下限和上限的方法。我不确定是否可能实现,并倾向于认为这是Java中通配符的当前限制。
以下是我正在寻找的示例:
public class A {}
public class B extends A{}
public class C extends B{}
public class D extends C{}
public static void main(String[] args)
{
List<A> a = Arrays.asList(new A());
List<B> b = Arrays.asList(new B());
List<C> c = Arrays.asList(new C());
List<D> d = Arrays.asList(new D());
extendsParam(a); // error as A is not assignable to B
extendsParam(b);
extendsParam(c);
extendsParam(d); // 3 previous ok as they can produce B
superParam(a);
superParam(b);
superParam(c); // 3 previous ok as they can consume C
superParam(d); // error as C is not assignable to D
extendsSuperParam(a); // error as A is not assignable to B
extendsSuperParam(b);
extendsSuperParam(c); // 2 previous ok as they can consume C and produce B
extendsSuperParam(d); // error as C is not assignable to D
}
public static void extendsParam(List<? extends B> blist)
{
B b = blist.get(0);
blist.add(new C()); // error
}
public static void superParam(List<? super C> clist)
{
B b = clist.get(0); // error
clist.add(new C());
}
public static void extendsSuperParam(List<???> bclist)
{
B b = bclist.get(0); // ok
bclist.add(new C()); // ok
}
看起来,在通用类型信息的WildcardType.java
类中,它支持使用该信息定义一种类型。然而,我无法找到在语言中创建这种类型的方法。
我有遗漏什么吗?还是说这种类型目前无法用Java语言来描述?
B
并添加C
,请使用List<B>
。有界通配符为调用API的人提供了灵活性-请参见什么是PECS(生产者扩展消费者超级)?。 - SlawList<B>
,那么即使List<C>
是他们可以使用的完全合法的类型,他们也不能传入它。我可以为B
和C
之间每种可能的类型都添加一个方法,但是对于大型类层次结构或B
和C
本身是泛型类型的情况,这将变得难以处理。 - gline9java.lang.reflect.WildcardType
和javax.lang.model.type.WildcardType
。 - Slaw