Reputation: 2101
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
.
Upvotes: 4
Views: 2158
Reputation: 2832
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
Upvotes: 9
Reputation: 4272
Super s = (Super) Class.forName(str).newInstance();
i guess this will work.
Upvotes: 3
Reputation: 30855
here is the example
try{
Class my_class = Class.forName(class_name);
// use my_class object to
Object initClassObj = my_class.newInstance();
}catch(ClassNotFoundException ex){
// handle exception
}catch(Exception ex){
// handle other exception
}
Upvotes: 0