我有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) { ... }
}
最佳答案
没问题,它可行。
检查以下代码段:
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");
}
}