Search code examples
javareflectionclassloader

NoClassDefFoundError with java reflection


I am using the following code to dynamically load a class in java:

URL url = new File(ACTIONS_PATH).toURI().toURL();
URLClassLoader clazzLoader = new URLClassLoader(new URL[]{url});
Class<RatingAction> clazz =  (Class<RatingAction>) clazzLoader.loadClass(name);
return clazz.newInstance(); 

This code works with simple classes (no inheritance or interfaces), but the class I want to load is implementing an interface (that the class loader can find using findClass) and when i call class.newInstance I get the mentioned exception. What am i doing wrong?

Thank you.


Solution

  • You have problems with your classpath. My guess it happens since you don't define the parent classloader - does "url" contains all the needed classes including the system classes?

    You are getting the exception, when the class is actually resolved, so the classes that appear in the loaded class are also loaded. If you change clazzLoader.loadClass(name) to clazzLoader.loadClass(name, true), you will get the exception in loadClass line.

    Try the following:

    URL url = new File(ACTIONS_PATH).toURI().toURL();
    URLClassLoader clazzLoader = new URLClassLoader(new URL[]{url}, getClass().getClassLoader());
    Class<RatingAction> clazz =  (Class<RatingAction>) clazzLoader.loadClass(name);
    return clazz.newInstance();