18

I know it's possible to add multiple constraints to a Generic class definition, e.g.:

class Example<I extends Object & Comparable<Object>>{}

But I want a generic (MyGeneric) that takes another generic (SomeGeneric<T>) as its type parameter, and to constrain the type parameter (T) of that generic (e.g. T extends SomeClass).

Important, I need to know the types of both SomeGeneric and SomeClass from inside the class (G and T need to both be bound). For example, imagine something like this:

class MyGeneric<G extends SomeGeneric<T>, T extends SomeClass>
{
   public G returnSomeGenericImpl(){}
   public T returnSomeClassImpl(){}
}

Question: The above works, but I would prefer if my class had only one type parameter, to make life easier for implementers of my class. Is there a way of doing this?

Something like this would be nice (but this particular code is incorrect):

class MyGeneric<G extends SomeGeneric<T extends SomeClass>>
{
   public G returnSomeGenericImpl(){}
   public T returnSomeClassImpl(){}
}

If I wasn't clear, I'll gladly try to clarify my intent.

4

3 回答 3

1

尝试这个

class Test1<T extends List<? extends Number>> {

    public static void main(String[] args) throws Exception {
        new Test1<ArrayList<Number>>();  
        new Test1<ArrayList<Integer>>(); 
        new Test1<ArrayList<Object>>();  // compile error
    } 
}
于 2013-05-15T12:37:54.117 回答
1

看起来不可能实现。

通过删除一个类型变量并尝试定义它,将您的类型定义减少一阶后,

class G extends SomeGeneric<T extends SomeClass>{}

无法编译,因为类型参数 T 未绑定到已定义的类型参数。但是,这行得通 -

class G<T extends SomeClass> extends SomeGeneric<T>{}

因此,我推断使用两种类型进行参数化的唯一方法是预先声明它们。

于 2013-05-15T19:34:20.317 回答
0

想象一下:

Type t = someClass();
Type g = someGeneric(t);

foobar(g,t)

与此相比

Type g = someGeneric(someClass());
foobar(g,?)

第二个是 Evgeniy Dorofeev 的解决方案。你看到问题了吗?您不能绑定到参数中的变量。与泛型相同。你想做的是这个

Type g = someGeneric(Type t = someClass());
foobar(g,t)
于 2013-05-16T04:45:27.933 回答