I would like to create an object dynamically.
I have the following structure: 1 abstract class and several classes that inherit from the abstract class
abstract public class A {..}
public class B extends A{..}
public class C extends A{..}
I have a config file where i want to add a class name, to have the ability to control which class it should be used.
# config class name
classname = B
I tried the following, but here I have the problem that I have to cast the result and I do not know how I can do it dynamically at this point
public class TestClass {
public A instB;
public void getInstance(){
this.instB = Class.forName("B") /*here i put later the config value classname*/
.getConstructor(String.class)
.newInstance(new Object[]{"test"}); // <--- How to cast this dynamicly to a class in the config?
}
}
How can I dynamically create an instance of a class?
newInstance, provide your arguments, likenewInstance("test")and then you have to manually cast, like(A) Class.forName(...)....instanceofis obsolete ifBextendsA.A, and you may want to handle that before an exception is thrown.isAssignableFrombefore running the constructor, though, rather than useinstanceof, as the constructor may have unwanted side effects in case it's not the appropriate class.