Search code examples
javaspringclassexceptionclassnotfoundexception

An equivalent for a Class.forName call without exception handling


I was wondering if there is "a method-wrapper" over the method Class.forName(className) which throws an unchecked exception if the checked ClassNotFoundException happens.

My problem is to handle these types of exceptions inside a lambda body. It looks too scruffy:

definition -> {
    new Thread(() -> {
        try {
            context.getBean(Class.forName(definition.getBeanClassName()));
            ...
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }).start();
});

Or do I have to write my own?

Thanks in advance.


Solution

  • Spring knows the org.springframework.util.ClassUtils.resolveClassName method which is an equivalent for Class.forName but throwing an IllegalArgumentException if the class cannot be found.