質問

I want to ask about UrlClassLoaders. I write a main .jar file which works well. Now I want to make it able to load plugins from one of its folders. I wrote it until that it finds the .jar files in the folder, can list their classes inside (their name, path). The problem is when I ask him to find that class (for create an instance of it) they won't find the class which it inherites from my main jar file like this:

IN MAIN JAR:
-class Expansion { ... }

In a plugin jar:
-class ExpansionA extends MainJar.Expansion { ... }

So when I ask an UrlClassLoader to resolve the "ExpansionA" class it will search for the "Expansion" class in the plugin jar instead of the MainJar, and there is no "Expansion" class in the plugin jar because it inherites from the MainJar as a resource library... and throws NoDefFoundForClassError exception while the defineClass method. How can I tell him to check after the classes in the MainJar too? (Its not only about 1 class but I want the plugin to be able to inherite any class from the MainJar). Can u help me?

役に立ちましたか?

解決

ClassLoaders have a parent to which load requests are delegated first. To ensure that the new class loader you are creating can access the class Expansion you should set the parent of the new ClassLoader to the ClassLoader of your class Expansion:

ClassLoader myLoader=newURLClassLoader(urls, Expansion.class.getClassLoader());

This does not only ensure that the Expansion class will be found by myLoader, it will also guaranty that it resolves to the same runtime class (as the parent is asked first). This is important if the plugin jar contains a copy of the class.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top