我有一个需要像这样动态初始化的类: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();}与示例类(以下相同模式中的许多类之一)配对:public class classnameOne implements TestInterface {
@Inject
private Logger log;
// ...
@Override
public void doStuff() {
// Do stuff
log.info("done");
}}问题是log在classnameOne类中null初始化时log.info()会调用并因此抛出NullPointerException。我需要那个记录器,所以有没有可能在创建类时初始化注入的属性newInstance()?或者是否还有其他可能基于字符串动态创建对象?
添加回答
举报
0/150
提交
取消