Defining a method as
myMethod(Object... obj){}
allows arbitrary number and types of parameters to be used.
I'd love to use generics for strict definition of the number and types of parameters.
For example, Let's assume that the above mentioned myMethod(Object...)
is a method in a class named MyClass
and MyClass
can be instantiated by default constructor.
I need to define instances in a way similar to this:
MyClass<Integer, Integer, String> instance1 = new MyClass<Integer, Integer, String>();
MyClass<String, String, Integer, Integer> instance2 = new MyClass<String, String, Integer, Integer>();
so the type definitions above will set the number and types of parameters allowed on calls to myMethod()
:
instance1.myMethod(1, 2, "test");
instance2.myMethod("one", "two", 1, 2);
The question is: How to define MyClass
in such a way that will allow any number of type parameters?
Any advice will be appreciated.
You can't, number of type parameters is fixed per class. you can play crazy tricks
class Tuple
{
Object[] objects() { return ...; }
}
class Tuple1 ...
class Tuple2 ...
class Tuple3<T1,T2,T3> extends Tuple
{
static public<S1,S2,S3> Tuple3<S1,S2,S3> of(S1 o1, S2 o2, S3 o3){ return ...; }
}
class Tuple4<T1,T2,T3,T4> extends Tuple
{
static public<S1,S2,S3,S4> Tuple4<S1,S2,S3,S4> of(S1 o1, S2 o2, S3 o3, S4 o4){ return ... ; }
}
...
class Tuple9 ...
class MyClass<TupleN extends Tuple>
{
void myMethod(TupleN ntuple)
{
Object[] objects = ntuple.objects();
// work on objects
}
}
MyClass<Tuple3<Integer,Integer,String>> instance3 = new MyClass<Tuple3<Integer, Integer, String>>();
instance3.myMethod( Tuple3.of(1,2,"test") );
It's not worth it. Sometimes you have to give up extraneous type checking for simplicity.
I don't think what you're trying to do can be achieved, but perhaps you could give some indication of what myMethod()
does?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With