Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variable length type parameters in generic class definition

Tags:

java

generics

Is it possible to add variable number of generic parameters in class definition?

Ex:

public class Test<E,T,U...>

And the exact number of generic parameters to be defined while building the instance of the object.

like image 791
g.kanellis Avatar asked Dec 05 '25 09:12

g.kanellis


1 Answers

Apparently you want to be able to make Test take multiple parameters of different types in the form of varargs.

VarArgs are actually being passed as an Array but you can't have an array with different types of objects in it.

However, Can't we instead take a single parameter and that parameter type holds each of the individual "parameters" that needs to be used.

class TypedInstance<T>{
   Class<T> type;
   T instance;
}

Or

Different classes for each set of parameters you want to use. Then just pass that class as a param.

 class MultiTypedInstanceType1<T, R>{
    public R doSomething(T t){ .... }
}

 class MultiTypedInstanceType2<T, R, P>{
    public R doSomething(T t, P p){ .... }
}
like image 62
Rahul Avatar answered Dec 06 '25 21:12

Rahul