开发者

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 URLClassLoade开发者_高级运维r(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.


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(); 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜