samedi 26 janvier 2019

how to instantiate objects that implement an interface with reflection in Java

I have a set of classes that extend a generic class. This class in turn implements an interface. I want to be able to instantiate the objects that extent this class based on some string value, using reflection.

Interface

public interface Vehicle {
    public String reportStats();
}

Generic Class

public class Premium implements Vehicle {
    public String reportStats() {
        return "generic stats";
    }
}

One type

public class Volvo extends Premium {

    public void drive() {
         // impl
    }
}

Another type

public class Mercedez extends Premium {

    public void drive() {
         // impl
    }
}

Trying to instantiate using reflection

String objectStr = "org.test.project.impl.Volvo";
Class<? extends Vehicle> vehicleClass;
vehicleClass = (Class<? extends Vehicle>) Class.forName(objectStr);

// this does not work
// the error that i get is Volvo cannot be casted to Vehicle
Vehicle vehicle = vehicleClass.cast(vehicleClass.newInstance());
String stats = vehicle.reportStats();

What is the proper way of dynamically instantiating an object, based on string input, in order to be able to trigger inherited methods?

Thanks.





Aucun commentaire:

Enregistrer un commentaire