Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to have a variable amount of Element types in a java generic class

Tags:

java

generics

I was wondering if it is possible to have something like this:

public class foo<T...>

so you can call the class like

Foo<Object0>
Foo<Object0, Object1>
Foo<Object0, Object1, Object2>

With Object 0, 1 and 2 different types, like Integer, Float, String and so on. Is this possible, or would I have to write a class for each lenght of generic types? If this would be possible, how would I handle the different types?

like image 821
Rheel Avatar asked May 19 '13 12:05

Rheel


1 Answers

No, you can't have that. The best you can do is public class Foo<T extends SomeClassOrInterface>. So in your example with Integer and Float you can define public class Foo<T extends Number>.

You can also specify that T must implement more than one interface.

The syntax public class Foo<T extends SomeInterface1 & SomeInterface2> is valid, with & meaning AND.

Unfortunately the syntax public class Foo<T extends SomeInterface1 | SomeInterface2> with | meaning OR is not possible.

like image 143
nakosspy Avatar answered Oct 13 '22 23:10

nakosspy