Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Generic with 1 type parameter and 2 constraints

Tags:

java

generics

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.

like image 510
Alex Averbuch Avatar asked May 15 '13 11:05

Alex Averbuch


People also ask

Can generics take multiple type parameters?

Multiple parametersYou can also use more than one type parameter in generics in Java, you just need to pass specify another type parameter in the angle brackets separated by comma.

Can a generic class have multiple constraints?

There can be more than one constraint associated with a type parameter. When this is the case, use a comma-separated list of constraints. In this list, the first constraint must be class or struct or the base class.

Can a generic class have multiple generic parameters Java?

A Generic class can have muliple type parameters.

How many type parameters can a generic class introduce?

Generic Classes As with generic methods, the type parameter section of a generic class can have one or more type parameters separated by commas. These classes are known as parameterized classes or parameterized types because they accept one or more parameters.


1 Answers

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.

like image 130
Seeta Somagani Avatar answered Sep 22 '22 15:09

Seeta Somagani