是否可以在命名的通用类型上强加上限(超级X)?

Nic*_*cue 9 java generics wildcard super

假设我有以下静态方法和接口(List是java.util.List).请注意,静态方法对列表的通配符类型强制执行"super Foo".

public class StaticMethod {
   public static void doSomething(List<? super Foo> fooList) {
      ...
   }
}

public interface MyInterface<T> {
   public void aMethod(List<T> aList);
}
Run Code Online (Sandbox Code Playgroud)

我希望能够使用静态方法添加一个实现接口的类,如下所示:

public class MyClass<T> implements MyInterface<T> {
   public void aMethod(List<T> aList) {
     StaticMethod.doSomething(aList);
   }
}
Run Code Online (Sandbox Code Playgroud)

这显然不会编译,因为T没有"超级Foo"约束.但是,我看不到任何添加"超级Foo"约束的方法.例如 - 以下内容不合法:

public class MyClass<T super Foo> implements MyInterface<T> {
   public void aMethod(List<T> aList) {
     StaticMethod.doSomething(aList);
   }
}
Run Code Online (Sandbox Code Playgroud)

有没有办法解决这个问题 - 理想情况下没有改变StaticMethodMyInterface

Boh*_*ian 1

我在这里冒险,但我认为下界是这里的问题,因为当您引用它时,您必须知道适合该边界的实际类......您不能使用继承。

这是一个可以编译的用法,但请注意,我需要命名实际的 Foo 的超类:

class SomeOtherClass
{
}

class Foo extends SomeOtherClass
{
}

class StaticMethod
{
    public static <T> void doSomething(List<? super Foo> fooList)
    {
    }
}

interface MyInterface<T>
{
    public void aMethod(List<T> aList);
}

class MySpecificClass implements MyInterface<SomeOtherClass>
{
    public void aMethod(List<SomeOtherClass> aList)
    {
        StaticMethod.doSomething(aList);
    }
}
Run Code Online (Sandbox Code Playgroud)

评论?

ps我喜欢这个问题:)