Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java variable number of generics

I need a way to implement a class that can take in a variable number of generic parameters. Basically, I need a way to combine the following classes:

class IncidentReporter1<A> {
    public void reportIncident(A a) {
    }
}
class IncidentReporter2<A, B> {
    public void reportIncident(A a, B b) {
    }
}
class IncidentReporter3<A, B, C> {
    public void reportIncident(A a, B b, C c) {
    }
}
class IncidentReporter4<A, B, C, D> {
    public void reportIncident(A a, B b, C c, D d) {
    }
}

into just one IncidentReporter class. I know I can take in a Class[] at runtime and use that, but I was wondering if there was a better native way to do this in java.

like image 668
akarshkumar0101 Avatar asked Aug 10 '17 18:08

akarshkumar0101


Video Answer


1 Answers

I would probably just write it like this :

public class IncidentReporter {

public void reportIncident(Class<?>... differentClasses) {

}

}

Much cleaner i think.

like image 116
Ndumiso Avatar answered Oct 18 '22 04:10

Ndumiso