Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 because 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?

like image 544
Nick Fortescue Avatar asked Jun 04 '11 10:06

Nick Fortescue


1 Answers

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 :)

like image 64
Bohemian Avatar answered Sep 22 '22 11:09

Bohemian