简体   繁体   中英

Generics + optional parameter in Java can't be combined

I am searching for an 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 issue is that you cannot simply invoke this method with:

myMethod(ImplA.class, ImplB.class);

This is just simply not accepted. Is it true that optional parameter and generics can't be combined? I cannot find any example.

I would try

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

Class<MyInterface> has to be MyInterface.class not a subclass.

Use the ? extends ? extends wildcard to get it to work.

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

The way you originally did it requires that the reference type of each implementer is MyInterface . With my proposed way, you are allowed to have your references be MyInterface or any child (grandchildren, etc) of MyInterface .

You have to make the argument type covariant (define an upper bound). There is only one type which 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
}

You can try something like this:

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

You should use bounded wildcard for declaring your generic 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);
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM