OSGI R4.2 (thus Equinox 3.5) comes (well, will come, since the spec. is not final yet) with a new simple and handy utility: the org.osgi.framework.FrameworkUtil.getBundle(Class) static method, which allows to retrieve the bundle a given class belongs to.
More specifically, this method will give you the bundle who loaded the given class, or null if the class has not been loaded by the OSGi framework (e.g. if it is a class belonging to the boot classpath…).
Thus, whenever you want to access information such as the version of a bundle, its headers, etc. without having to query its Activator (perhaps you don’t even have an Activator for this bundle…), you know what you’ve got to use! Of course, whoever says Bundle, means BundleContext, and this handy helper is also very convenient to easily publish/consume OSGi services on behalf of the bundle…
The post Given a class, how to retrieve its bundle? appeared first on Benjamin Cabé.