Generics + optional parameter in Java cannot be combined

I am looking for elegant solutions for the following problem:

//one interface public interface MyInterface () { } //two implementations public class ImplA implements MyInterface (){ } public class ImplB implements MyInterface () { } 

In another class:

 //one generic method public void myMethod(Class<MyInterface>... myTypes) { for (Class<MyInterface> myType : myTypes) { System.err.println("my Type:" +myType); } } 

The problem is that you cannot just call this method with:

 myMethod(ImplA.class, ImplB.class); 

It is simply not accepted. Is it true that optional parameters and generics cannot be combined? I can not find any example.

+4
source share
5 answers

I would try

 public void myMethod(Class<? extends MyInterface>... myTypes) { 

Class<MyInterface> must be MyInterface.class not a subclass.

+2
source

Use a template ? extends ? extends to make it work.

 public void myMethod(Class<? extends MyInterface>... myTypes) { for (Class<? extends MyInterface> myType : myTypes) { System.err.println("my Type:" +myType); } } 

As you did, it is required that the reference type of each artist is MyInterface . With my proposed method, you are allowed to have your links MyInterface or any child (grandchildren, etc.) MyInterface .

+1
source

You must make the type of the argument covariant (define the upper bound). There is only one type that has the signature Class<X> , and that is X.class . Subtypes are of type Class<? extends X> Class<? extends X> . So:

 @SafeVarargs public void myMethod(Class<? extends MyInterface>... myTypes) { // do stuff } 
+1
source

You can try something like this:

 public void myMethod(Class<? extends MyInterface>... myTypes) { for (Class<?> myType : myTypes) { System.err.println("my Type:" +myType); } } 
0
source

You must use a restricted template to declare your type type - Class<? extends MyInterface> Class<? extends MyInterface>

 public void myMethod(Class<? extends MyInterface>... myTypes) { for (Class<? extends MyInterface> myType : myTypes) { System.err.println("my Type:" +myType); } } 
0
source

Source: https://habr.com/ru/post/1432493/


All Articles