Martin Schlagnitweit
Martin Schlagnitweit

Reputation: 2101

How to get a SubClass Instance, when i know the Class name as String in java?

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

Answers (3)

Mateusz Chromiński
Mateusz Chromiński

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

amod
amod

Reputation: 4272

Super s = (Super) Class.forName(str).newInstance();

i guess this will work.

Upvotes: 3

Pratik
Pratik

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

Related Questions