I have a class that needs to be initialized dynamically like this:
void doSth(classsuffix) throws Exception {
String classname = "org.test.classname" + classsuffix; // classsuffix is dynamic
Class<?> clazz;
clazz = Class.forName(classname);
TestInterface test = (TestInterface) clazz.newInstance();
test.doStuff();
}
Paired with a example class (one of many following the same pattern):
public class classnameOne implements TestInterface {
@Inject
private Logger log;
// ...
@Override
public void doStuff() {
// Do stuff
log.info("done");
}
}
The problem is that log in the classnameOne class will be null when initialized and the log.info() call will therefore throw a NullPointerException.
I need that logger to be there though, so is there any possibility to initialize injected properties when creating the class with newInstance()?
Or is there any other possibility to create objects dynamically based on a string?