Categories
Eclipse

Retrouver le bundle auquel appartient une classeGiven a class, how to retrieve its bundle?

OSGI R4.2 (donc Equinox 3.5) introduit une nouveauté toute bête, mais particulièrement pratique. Il s’agit de la méthode org.osgi.framework.FrameworkUtil.getBundle(Class), qui permet de récupérer le bundle auquel appartient une classe donnée.

Plus précisément, cette méthode vous renverra le bundle qui a servi à résoudre ladite classe, ou null dans le cas où la classe n’a pas été chargée par le Framework (si c’est une classe du boot classpath par exemple…).

Ainsi, dès qu’il s’agira de récupérer des infos comme le numéro de version d’un bundle, ses headers, etc… sans avoir à passer par l’Activator (qui parfois n’existe d’ailleurs même pas…), vous savez ce qu’il vous restera à faire! En outre, qui dit Bundle, dit BundleContext, et cette méthode est donc également un moyen très simple de publier/consommer des services !.. 🙄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… 🙄