是否可以对命名的Generic类型施加上限(super X)



假设我有以下静态方法和接口(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);
}

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

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

这显然不会编译,因为t没有"super-Foo"约束。然而,我看不出任何添加"superFoo"约束的方法。例如,以下内容是不合法的:

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

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

我在这里遇到了一个问题,但我认为较低的边界是这里的问题,因为当你引用它时,你必须知道符合边界的实际类……你不能使用继承。

这里有一个编译的用法,但请注意,我需要命名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);
    }
}

评论?

p.s.我喜欢这个问题:)

如果您确定aList包含可以安全地转换为<? super Foo>的对象,那么您可以执行:

public static class MyClass<T> implements MyInterface<T> {
    @Override
    public void aMethod(List<T> aList) {
        StaticMethod.doSomething((List<? super Foo>) aList);
    }
}

请参阅完整的工作示例:http://ideone.com/fvm67

最新更新