I want to create instances of java classes (which all extend a superclass) at runtime.
Here some Example classes:
class Super {
}
class FirstSub extends Super {
}
class SecondSub extends Super {
}
I know the class name as string:
String name = "SubClassName";
This was my first approach:
Super foo;
if (FirstSub.class.getSimplename().equals(name)) {
foo = new FirstSub();
}
if (SecondSub.class.getSimplename().equals(name)) {
foo = new SecondSub();
}
How do i get an instance of one of the “subclasses” in a more sophisticated way?
EDIT: Additionally I want to cast foo to SubClassName.
Dynamically casting that your variable reference will be Subclass is impossible and non-worthy. If in this place your object could be FirstSub or SecondSub then both of this object should provide some given functionality (method). You should define some (e.g. abstract) method in superclass (or make it interface). Then, if you have such line:
where o is instance of subclass of Super, then invoking your method would invoke method on subclass. This is beauty of polymorphism