简体   繁体   English

Java中的泛型+可选参数无法组合

[英]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. Class<MyInterface>必须是MyInterface.class而不是子类。

Use the ? extends ? extends ? extends wildcard to get it to work. ? extends通配符以使其工作。

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 . 您最初的方式要求每个实现者的引用类型是MyInterface With my proposed way, you are allowed to have your references be MyInterface or any child (grandchildren, etc) of MyInterface . 随着我的建议的方式,你都不允许有你的介绍人是MyInterface或任何子女(孙子,等) MyInterface

You have to make the argument type covariant (define an upper bound). 您必须使参数类型为covariant(定义上限)。 There is only one type which has the signature Class<X> , and that is X.class . 只有一种类型具有签名Class<X> ,即X.class Subtypes are of type Class<? extends X> 子类型是Class<? extends X> 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> Class<? extends MyInterface>

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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