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();
This appears to be working if the classes are in the same jar, but if Mercedez or Volvo are factored out into a separate jar, under the same package, the cast fails with a java.lang.ClassCastException.
Thanks.