Panda
Panda

Reputation: 1537

How does one give the Class Object an upper bound generic?

I have 2 interfaces and 2 classes:

interface MyInterface1 { ... }
interface MyInterface2 extends MyInterface1 { ... }

class MyClass1 implements MyInterface1 { ... }
class MyClass2 implements MyInterface2 { ... }

I want to be able to specify classes such that the Class Object can only be at least of type MyInterface1 (which includes all classes that are at least of MyInterface2, right?). I thought it might work with Class<? extends MyInterface1>; however, this only allows classes that directly implement MyInterface1 and not MyInterface2.

A more specific implementation follows:

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

Upvotes: 0

Views: 74

Answers (1)

Soroosh Sarabadani
Soroosh Sarabadani

Reputation: 439

There is no problem and it works.

Check the below code snippet:

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

    }

}

Upvotes: 1

Related Questions