lundi 20 avril 2015

Using reflection to create an instance based on getClass of generic class

I would like to know what is the right way to declare Class<...> stateBaseClass, when my goal is to create an instance by using Reflection: state = stateBaseClass.newInstance(); without using cast.

I put some comments in the code below:

abstract class StateBase{} // It is so complex to be serializable.

class State extends StateBase{}

class StateInstanceDescription <T extends StateBase> implements Serializable{ 
    private static final long serialVersionUID = -828114417567233018L;

    transient private T stateBase;

    // what is the right way to declare the line below to void that cast?
    private Class<? extends StateBase> stateBaseClass; 

    public StateInstanceDescription(T base){
        this.stateBase = base;
        stateBaseClass = base.getClass();
    }

    public T getBase() {
        return stateBase;
    }

    public Class<? extends StateBase> getBaseClass() {
        return stateBaseClass;
    }

}

public class Main {
    public static void main(String ... args) throws InstantiationException, IllegalAccessException{
        State state = new State();
        StateInstanceDescription<State> stateInstDesc = new StateInstanceDescription<>(state);

        // ... At some point, I will recreate State after deserialize stateInstDesc.
        // compiler-time error. Compiler is asking for casting it to (State). 
        // There is a way to avoid this cast?
        state = stateInstDesc.getBaseClass().newInstance(); 
    }
}





Aucun commentaire:

Enregistrer un commentaire