2013-05-06 254 views
2

在我以前的问题中,我问如何加载远程jar文件。我当前的代码是这样的:URLClassloader依赖关系

//f is the path to the jar 
URLClassLoader loader = new URLClassLoader(new URL[]{f.toURI().toURL()}); 
Class<?> jarClass = Class.forName(main, true, loader); 
Class<? extends Module> module = jarClass.asSubclass(Module.class); 

Constructor<? extends Module> constructor = module.getConstructor(); 
System.out.println(constructor); 

Module module = constructor.newInstance(); 

这种运作良好,但远程加载的模块扩展类是在加载它们的罐子,这给了这个错误:

造成的:JAVA。 lang.ClassNotFoundException:package.whatever.Module,我认为这是因为它使用URLClassLoader而不是getClass()。getClassLoader()..我怎样才能让它使用URLClassLoader,然后回退到默认值?

感谢,
巴特

回答

1

你可以设置你的应用程序类加载器的URL类加载器的父:

URLClassLoader loader = new URLClassLoader(
     new URL[]{f.toURI().toURL()}, Module.class.getClassLoader()); 

Oracle Java tutorial(类加载机制):

The Java platform uses a delegation model for loading classes. The basic idea is that every class loader has a "parent" class loader. When loading a class, a class loader first "delegates" the search for the class to its parent class loader before attempting to find the class itself.

+0

非常感谢! – Bart 2013-05-06 21:01:56