开发者

Is it possible to impose an upper bound (super X) on a named Generic type?

开发者 https://www.devze.com 2023-03-11 12:45 出处:网络
Suppose I have the following static method and interface (List is java.util.List). Note that the static method enforces a \"super Foo\" on the wildcard type of the list.

Suppose I have the following static method and interface (List is java.util.List). Note that the static method enforces a "super Foo" on the wildcard type of the list.

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

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

I would like to be able to add a class which implements the interface using the static method as follows:

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

This obviously won't compile becaus开发者_运维问答e T does not have the "super Foo" constraint. However, I can't see any way of adding the "super Foo" constraint. For example - the following is not legal:

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

Is there any way of solving this problem - ideally without altering StaticMethod or MyInterface?


I'm going out on a limb here, but I think lower bounding is the problem here, because you have to know about the actual class that fits the bound when you refer to it... you can't use inheritance.

Here's a usage that compiles, but notice that I need to name the actual class that is a super of 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);
    }
}

Comments?

p.s. I like the question :)


If you are sure that aList contains objects that can be safely cast to <? super Foo>, then you can do:

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

See the complete and working example: http://ideone.com/fvm67

0

精彩评论

暂无评论...
验证码 换一张
取 消