Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variadic Parameter of Class Types - Java

Tags:

java

generics

Take for instance, the method below.

<T extends MyInterface> void myFunction(Class<T>... types) {
    // Do some stuff that requires T to implement MyInterface
}

Now, given the method call below assuming MyClass1 and MyClass2 both implement MyInterface.

myFunction(MyClass1.class, MyClass2.class)

I get the following error.

Incompatible equality constraint: MyClass1 and MyClass2

How do I make this work? More specifically, how would one use a variadic parameter of class types implementing an interface in Java?

like image 312
Anthony Dito Avatar asked Dec 14 '25 10:12

Anthony Dito


2 Answers

You've declared T to have an upper bound of MyInterface. By passing in MyClass1.class and MyClass2.class, the compiler must infer MyInterface for T.

However, the type of the parameter type is Class<T>..., restricting what is passed in to MyInterface.class and no subtypes.

Depending on the "stuff" you're doing, you can place a wildcard upper bound on the type of types to get it to compile.

<T extends MyInterface> void myFunction(Class<? extends T>... types) {
like image 128
rgettman Avatar answered Dec 15 '25 23:12

rgettman


Having a T means that T has one fixed value, which means that all of the Class<T>... parameters must be the exact same type. The compiler cannot infer T==MyInferface because Class<MyClass1> is not a subclass of Class<MyInterface>.

You want to allow each parameter to have a different type. That requires a different signature:

void myFunction(Class<? extends MyInterface>... types)

There's no need for T at all.

like image 31
John Kugelman Avatar answered Dec 16 '25 00:12

John Kugelman