Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

generics multiple types

Tags:

java

generics

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.

like image 951
Joel Shemtov Avatar asked Dec 14 '22 00:12

Joel Shemtov


2 Answers

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.

like image 167
irreputable Avatar answered Jan 03 '23 19:01

irreputable


I don't think what you're trying to do can be achieved, but perhaps you could give some indication of what myMethod() does?

like image 24
harto Avatar answered Jan 03 '23 21:01

harto