2013-05-06 307 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