简体   繁体   English

Java 通配符类型的下限和上限

[英]Lower and Upper Bound for Java Wildcard Type

I've looked around and so far haven't seen any way of having both a lower and upper bound on the same wildcard type in java.我环顾四周,到目前为止还没有看到任何方法可以在 java 中对相同的通配符类型同时设置下限和上限。 I'm not sure if it is possible and am leaning towards it being a current limitation of wildcards in java.我不确定这是否可能,并且倾向于将其作为 Java 中通配符的当前限制。

An example of what I'm looking for is below.我正在寻找的一个例子如下。

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
}

Looking at the WildcardType.java class for the generic type information it looks like it supports defining a type with that information.查看WildcardType.java类的泛型类型信息,它似乎支持使用该信息定义类型。 However, I cannot find a way to create such a type in the language.但是,我找不到在语言中创建这种类型的方法。

Is there something that I'm missing or is this a type that is currently impossible to describe with the java language?是否有我遗漏的东西,或者这是目前无法用 java 语言描述的类型?

This can't be done according to the Oracle Docs :根据Oracle Docs无法做到这一点:

Note: You can specify an upper bound for a wildcard, or you can specify a lower bound, but you cannot specify both.注意:您可以为通配符指定上限,也可以指定下限,但不能同时指定两者。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM