Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 899
Martin Schlagnitweit Avatar asked Dec 16 '22 10:12

Martin Schlagnitweit


1 Answers

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

like image 71
Mateusz Chromiński Avatar answered Feb 02 '23 01:02

Mateusz Chromiński