11
votes

With the import mechanism in OSGi, it is straightforward to import packages from another bundle. However, I have been unsuccessful in importing resources that exist in the "root" of the bundle.

Is it at all possible to import resources that aren't package scoped in to another bundle?

What I would like to achieve is this:

Bundle A has a file resource in the "root"

Bundle B imports bundle A:s packages and resources. Through bundle B:s ClassLoader, I'd like to be able to load the resource in bundle A as if it existed in Bundle B.

3
i am also looking for exactly this, the only method i can think of is by getting it directly from the jar without using osgi, download.oracle.com/javase/tutorial/uiswing/components/… .. but this defeats the purpose of osgi i guess - FUD

3 Answers

10
votes

Resources in the root of a bundle are in the "default" package, which cannot be imported or exported.

If you really must access the resources via classloader, you need to move them into a package and export that package. Otherwise you can use Bundle.getEntry() to read resources from any location of any bundle.

1
votes

You can use OSGi Fragment bundles. For your case: bundle B is a host and bundle A is a fragment of the bundle B. But bundle B has access to all classes and resources (folders) of bundle A.

More details in OSGi Core Spec #3.13 Fragment bundles

0
votes

Create a new thread and then create a new classloader that points to the files needed.

Look at this fragment:

ClassLoader c = new URLClassLoader(urls);
thread.setContextClassLoader(c);

The thread classloader will then be able load the files within the package where the URLs include the absolute location to the bundle.