I have read a lot of equinox code for this, but still can't figure out a non-hacky way of getting the classloader for a osgi bundle in eclipse equinox setup. Is there one?
Asked
Active
Viewed 1.7k times
4 Answers
40
In OSGi 4.3 you can use:
bundle.adapt(BundleWiring.class).getClassLoader()

Timo
- 2,212
- 2
- 25
- 46

Balazs Zsoldos
- 6,036
- 2
- 23
- 31
11
The short answer (certainly for OSGi 4.1, not sure of 4.2) is you can't get a bundle's classloader. However the Bundle
interface exposes a loadClass()
method and this would allow you to write a classloader that wraps the bundle API and delegates to that loadClass()
method. Or you can save some time and use Spring DM's BundleDelegatingClassLoader
class instead.

SteveD
- 5,396
- 24
- 33
6
The class loader of a bundle can be obtained through the BundleWiring interface. Here a short example:
Bundle bundle = bundleContext.getBundle();
BundleWiring bundleWiring = bundle.adapt(BundleWiring.class);
ClassLoader classLoader = bundleWiring.getClassLoader();

tux2323
- 61
- 1
- 1
2
In normal java code, you can get the class loader that loaded a given object with
object.getClass().getClassLoader();
Or even just
SomeType.class.getClassLoader();
The same applies to Equinox, just use an object or type that comes from the bundle you are interested in.

Andrew Niefer
- 4,279
- 2
- 19
- 22
-
1But then you have a bootstrapping problem. How do you get that first instance? – Geniedesalpages Feb 24 '11 at 13:44
-
If you have dependency on the other bundle, you can refer to the other class directly (SomeType.class) the osgi classloaders delegate between bundles so it still comes from the other classloader. If you don't have a dependency you need to get the Bundle object (using PackageAdmin) and use Bundle#loadClass as mentioned in the other answer. – Andrew Niefer Feb 27 '11 at 02:09
-
J2SE class loading does not fit for J2EE. http://stackoverflow.com/questions/34787419/pmd-rule-use-proper-class-loader-explaination – Poornan Jul 14 '16 at 02:26
-
This would not be the correct class loader. The class loader which was used to load the Bundle class generally will not be the same thing as the bundle acting as a class loader. A little more generally, the class loader of ClassLoader.class will generally not be the same as any given class loader instance. While in simple environments, these may turn out to be the same, in partitioned environments (OSGi, JavaEE) they will be different. – Thomas Bitonti Jun 08 '17 at 15:15