I know it's possible to add multiple constraints to a Generic class definition, eg:
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 (eg 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.
try this
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
}
}
It looks impossible to achieve.
After reducing your type definition by one order by removing one type variable and trying to define it,
class G extends SomeGeneric<T extends SomeClass>{}
does not compile because the type parameter T is not bound with respect to an already defined type parameter. But, this works -
class G<T extends SomeClass> extends SomeGeneric<T>{}
So, I infer that the only way of parameterizing with two types is by declaring them up front.
Imagine this:
Type t = someClass();
Type g = someGeneric(t);
foobar(g,t)
compared to this
Type g = someGeneric(someClass());
foobar(g,?)
the second one is Evgeniy Dorofeev's solution. You see the problem? You can't bind to a variable within an argument. Same with generics. What you want to do is this
Type g = someGeneric(Type t = someClass());
foobar(g,t)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.