Search code examples
javaspringreflectioninvocationtargetexception

InvocationTargetException trying to make new instance of service class


In my current project, when this method is called:

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;
}

the application triggers a InvocationTargetException caused by this error:

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

where basicService is the superclass for the class stored in the variable clazz.

Anyone can tell me what I am doing wrong here? What the right way to make a new instance of this class?

ps.: the line 51 in basicService is placed inside this method:

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

and the member dao is defined this way:

@Autowired
protected Dao<E> dao;

Solution

  • Ok, I solve this problem adding to my project a class named ApplicationContextHolder, with this code:

    @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;
        }
    
    }
    

    the final code for the function list_values(...) is that:

    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);
    }