lundi 28 mai 2018

Return a class, not an instance, of a concrete class that extends an abstract base class?

If I have a class hierarchy like this

AbstractSuperClass
    ConcreteClassA
    ConcreteClassB

is it possible to have a static method in AbstractSuperClass which returns the class - not an instance - of one of the two concrete classes?

I've tried returning Class<AbstractSuperClass>, but the IDE (Android Studio) says

Incompatible types.
Required: Class <com.example.AbstractSuperClass>
Found:    Class <com.example.ConcreteClassA>

Here's an example of what I'm thinking, but which isn't working:

public abstract class AbstractSuperClass{

    public abstract void someAbstractMethod();


    public static String getSomeText(){ 
        return "This is AbstractSuperClass"; 
    };

    public Class<AbstractSuperClass> getConcreteClass(int x){
        switch( x ){
            case 0: return ConcreteClassA.class;
            case 1: return ConcreteClassB.class;
        }
    }
}


public class ConcreteClassA extends AbstractSuperClass{
    public abstract void someAbstractMethod(){
        // Do something
    }

    public static String getSomeText(){ 
        return "This is ConcreteClassA"; 
    };
}



public class ConcreteClassB extends AbstractSuperClass{
    public abstract void someAbstractMethod(){
        // Do something
    }

    public static String getSomeText(){ 
        return "This is ConcreteClassB"; 
    };
}



AbstractSuperClass.getConcreteClass(1).getSomeText(); // Should return "This is ConcreteClassB"

Is this simply impossible in Java, or am I just doing it wrong?





Aucun commentaire:

Enregistrer un commentaire