Java 通配符类型的上下限
Lower and Upper Bound for Java Wildcard Type
我环顾四周,到目前为止还没有看到在 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
class 的通用类型信息,它看起来支持使用该信息定义类型。但是,我找不到在语言中创建这种类型的方法。
有没有我遗漏的东西,或者这是目前无法用 java 语言描述的类型?
按照Oracle Docs是做不到的:
Note: You can specify an upper bound for a wildcard, or you can specify a lower bound, but you cannot specify both.
我环顾四周,到目前为止还没有看到在 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
class 的通用类型信息,它看起来支持使用该信息定义类型。但是,我找不到在语言中创建这种类型的方法。
有没有我遗漏的东西,或者这是目前无法用 java 语言描述的类型?
按照Oracle Docs是做不到的:
Note: You can specify an upper bound for a wildcard, or you can specify a lower bound, but you cannot specify both.