Is there a way for one bundle to get the Bundle instance for another bundle from a ServiceReference?
I'm trying to create a bundle that watches servi开发者_运维技巧ce registrations and, depending on certain metadata embedded in the API bundle for the service interface, performs some additional tasks. The metadata consists primarily of one or more properties files, so my thought was to use Bundle.findEntries()
but since the metadata is embedded in the API bundle, I can't just do something like ServiceReference.getBundle().findEntries()
as this would try to find the properties in the service implementation bundle, not in the API bundle.
I thought about getting the service API class name from the ServiceReference
ObjectClass property and then using either the Package Admin service or FrameworkUtil.getBundle()
, but both of these require a Class
--but how do I get the Class
of the service interface? The bundle that's doing this work probably hasn't imported the Class's package, so Class.forName()
won't work.
My other option is to watch for both bundle and service events: the first creates a registry of bundles that contain the metadata, the second using the first when a service is registered. Before going down that path I'm looking to see if there's an easier way.
Disclaimer: I haven't tried this, but I'm reasonably sure it should do the job.
You can get the packagename from the ServiceReference
's ObjectClass
, so now we have that, we can find the package in the framework. Given a PackageAdmin packageAdmin
, you can do something like
public Bundle getExporterOf(String package, ServiceReference ref) {
ExportedPackage[] packages = packageAdmin.getExportedPackages(packageName);
if (packages == null) {
return null;
}
for (ExportedPackage package : packages) {
Bundle[] importers = package.getImportingBundles()) {
if (importers == null) {
continue;
}
for (Bundle bundle : importers) {
if (bundle.getBundleId() == ref.getBundle().getBundleId()) {
return package.getExportingBundle
}
}
}
}
What we're doing here, is find all packages with the given package name (there might be multiple), find the one that the bundle that registered the service imports, and get the bundle that exported that package. You can probably make the method a little nicer.
精彩评论