I have the following classes.
abstract class A{}
class B extends A{}
class C extends A{}
I need to create an object like this
A a = new B();
I get the class name of the subclass at runtime. So, I need to use reflection to create an object.
I have done this.
Class<?> klass = Class.forName(className);
Now I am not able to cast this class to the subclass.
I want to achieve
A a = klass.newInstance(); // returns Object
I want the object to be casted into the subclass (either B or C, decided on runtime)
How do I do this?
A a = (A)klass.newInstance();?switch (name) { case "B": return new B(); case "C": return new C(); default: throw new SomeException(); }? / What's wrong withClass.newInstance? Plenty. If you're going throughConstructor.newInstance, better to useasSubclassup front.