cacert
cacert

Reputation: 2797

eclipse plugin classloading error

In a eclipse plugin project I have a jar file from which I want to load class and call methods. These jars added in bundle classpath in manifest file. How to load these classes runtime, if I try it with urlclassloader I get java.lang.NoClassDefFoundError but I am sure class is there. I read that eclipse osgi based and use its own classloader, and probably I get this error because of this. but why ? Do anybody have a good explanation and practical solution to my problem ? Thank you.

Upvotes: 1

Views: 1804

Answers (2)

Sebastian
Sebastian

Reputation: 1722

I got a similar problem and here is my solution. It´s maybe a bit late but i hope it will help others with the same problem.

I noticed that the classloader from eclipse (osgi) doesen´t load the complete jar. It only loads the classes which are directly loaded via classloader.load(classname). So i just read all the classnames contained in the jar with the code from this question and iterate over all classNames by calling explicit classloader.load(classname). Here is a sample of the way i managed it:

private void loadClasses(final File jar) {
    final URL url = new URL("jar", "", "file:" + jar.getAbsolutePath() + "!/");
    final List<String> classNames = getAllClassNames(jar); //Code from above link in this method
    final URLClassLoader classloader = new URLClassloader(url, this.getClass().getClassLoader());
    for (String className : classNames) {
        classLoader.load(className);
    }
}

If you want to instantiate a class you can do it with

final Class<?> clazz = classLoader.load(className);
final T type = (T)clazz.newInstance();

Hope this helps.

Upvotes: 0

Mirco
Mirco

Reputation: 3016

This is a problem caused by OSGi's different class loading mechanism. First of all, check if you added the right import-declarations to you manifest. If the imports are right (and have the right version), they might not be visible because the JAR you are using is not exporting the needed classes. OSGi can only see classes which are exported. Using Eclipse, which means you are using Equinox as OSGi implementation, you might use Eclipse-Buddy-Classloading. Create a new project with the JAR and export everything. Now register this as a buddy of your main bundle - the main bundle now can see every class of the providing bundle.

And keep in mind that using class loaders in OSGi is 'evil'. Classes can not be identified by their fully qualified class name anymore.

Take a look at the OSGi core specification for more information about OSGi class loading (osgi.org) and http://rajakannappan.blogspot.de/2010/03/eclipse-classloading-and-buddy-policy.html

Upvotes: 3

Related Questions