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
.
Class myClass = Class.forName(name);
Object o = myClass.newInstance();
Super instance = (Super)o;
//Subclass instance2 = (Subclass)o;
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:
Super instance = (Super)o;
where o is instance of subclass of Super, then invoking your method would invoke method on subclass. This is beauty of polymorphism
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With