我有2个接口和2个类:
interface MyInterface1 { ... }
interface MyInterface2 extends MyInterface1 { ... }
class MyClass1 implements MyInterface1 { ... }
class MyClass2 implements MyInterface2 { ... }
我希望能够指定类,使Class
对象只能至少为MyInterface1
类型(包括至少为MyInterface2
的所有类,对吧? )。我认为它可能适用于Class<? extends MyInterface1>
;但是,这只允许直接实现MyInterface1
而不是MyInterface2
的类。
更具体的实施如下:
public interface Algorithm<E extends Solution<E>> { ... }
public interface EvoAlgorithm<E extends Solution<E>> extends Algorithm<E> { ... }
public class GeneticAlgorithm<E extends Solution<E>> implements EvoAlgorithm<E> { ... }
public class TSPNNAlgorithm implements Algorithm<TSPSolution> { ... }
public enum AlgorithmType {
//**this is where the compiler error is occuring**
GENETIC(GeneticAlgorithm.class),
//**no compiler error here**
NEAREST_NEIGHBOUR(TSPNNAlgorithm.class);
private AlgorithmType(Class<? extends Algorithm<?>> algorithmClass) { ... }
}
答案 0 :(得分:1)
没有问题,而且有效。
检查以下代码段:
interface MyInterface1 { }
interface MyInterface2 extends MyInterface1 { }
class MyClass1 implements MyInterface1 { }
class MyClass2 implements MyInterface2 { }
public class Program1 {
public static void main(String[] args) {
a(MyClass1.class);
a(MyClass2.class);
}
public static void a(Class<? extends MyInterface1> input){
System.out.println("OK");
}
}