InvocationTargetException尝试创建服务类的新实例

时间:2014-11-02 13:23:47

标签: java spring reflection invocationtargetexception

在我当前的项目中,调用此方法时:

public Collection<? extends Object> list_values() throws Exception {
    String nome = classe().getSimpleName();
    String nome_service = nome+"Service";
    String local_service = "com.spring.model."+nome;
    Class<?> clazz = Class.forName(local_service.toLowerCase()+"."+nome_service);
    Object serv = clazz.newInstance();
    Collection<? extends Object> list = (Collection<? extends Object>) serv.getClass().getMethod("lista").invoke(serv);
    return list;
}

应用程序触发由此错误引起的InvocationTargetException:

Caused by: java.lang.NullPointerException
    at com.spring.config.generic.service.basicService.lista(basicService.java:51)

其中basicService是存储在变量clazz中的类的超类。

任何人都可以告诉我这里做错了什么?制作这个类的新实例的正确方法是什么?

ps:basicService中的第51行放在此方法中:

@Transactional
public List<?> lista() {
    return dao.findAll();
}

并且成员dao以这种方式定义:

@Autowired
protected Dao<E> dao;

1 个答案:

答案 0 :(得分:0)

好的,我解决了这个问题,在我的项目中添加了一个名为ApplicationContextHolder的类,代码如下:

@Component
public class ApplicationContextHolder implements ApplicationContextAware {

    private static ApplicationContext context;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        context = applicationContext;
    }

    public static ApplicationContext getContext() {
        return context;
    }

}

函数list_values(...)的最终代码是:

public List<?> list_values() throws Exception {
    String nome = classe().getSimpleName();
    Class<?> clazz = Class.forName("com.spring.model."+nome.toLowerCase()+"."+nome+"Service");
    Object object = clazz.newInstance();
    ApplicationContextHolder.getContext().getAutowireCapableBeanFactory().autowireBean(object);
    return (List<?>) object.getClass().getMethod("lista").invoke(object);
}