NoRelect
NoRelect

Reputation: 608

Instanceof works if project is run from eclipse, but not when its exported

I am working on a project that has to dynamically load .jar files from a folder. It gets all files from the folder that end with .jar and then opens them. It then gets every file inside the jar file ending with .class and loads it. I am then checking if the class extends LeafPluginwith the following code:

Class<?> clazz = classloader.loadClass(classname);
Object object = clazz.newInstance();
if(object instanceof LeafPlugin){
     // Load LeafPlugin
}else{
     System.out.println("Class '" + classname + "' isn't a LeafPlugin");
}

While this works fine with the exported DemoPlugin inside eclipse, if the project is exported, the message that the class isn't a LeafPlugin gets printed out. What is causing this wierd behaviour?

I have this project in the build path of the plugin, so the LeafPlugin shouldn't be different.

I have tried using LeafPlugin.class.isAssignableFrom(clazz), but it didn't change anything. What could be different from running it inside eclipse to running it if it exported?

The whole code can be found here (It is quite a lot, so just take a look at the LeafPluginLoader)

Upvotes: 0

Views: 81

Answers (1)

ug_
ug_

Reputation: 11440

The problem is in how you defined your ClassLoader in your LeafPluginLoader. You did not provide the code for it in your question (its on your GitHub tho). You have it as

URLClassLoader cl = URLClassLoader.newInstance(urls);

The issue is this class loader knows nothing of your current LeafPlugin class. You need to pass the ClassLoader instance which also loaded the LeafPlugin class.

URLClassLoader cl = URLClassLoader.newInstance(urls, LeafPlugin.class.getClassLoader());


Now I dont know classloader behavior enough to really explain in detail why this is the case, however simply put you must do this because ClassLoaders have a scope of classes it knows about. When loading in your plugins if the Classloader which loaded them doesnt know about the LeafPlugin class then your going to have issues.

Upvotes: 1

Related Questions