如何为类对象提供上限泛型?

时间:2015-01-26 11:14:28

标签: java generics

我有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) { ... }
}

1 个答案:

答案 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");

    }

}