mercredi 21 décembre 2016

Using generic type to create instance instead of reflection in java

I have code that looks like follows:

public class Person{
    private Configuration configuration;
    public void act(){
        final Action action = new Factory().createAction(configuration);
        ....
    }
}

public class Factory{
    public Action createAction(Configuration configuration){
        Constructor<? extends Action> constructor =
                  configuration.getActionClass.
                  getConstructor(configuration.getClass());
        return constructor.newInstance(configuration);
    }
}

public class Configuration{
    private Class<? extend Action> actionClass;

    public void setActionClass(Class<? extend Action> cls){
        this.actionClass = cls;
    }

    public Class<? extend Action> getActionClass(){
        return this.actionClass;
    }
}

Each time act() is called, a new Action instance is created for some reason. I need to subclass Action and pass it to act().

So I use reflection on a factory method to achieve that. But it seems overkill and not type safe.

Is it possible to repalce reflection with a type safe method such like generics?





Aucun commentaire:

Enregistrer un commentaire