Pavel_K Pavel_K - 3 years ago 170
Java Question

Get bundle classes of private packages in another bundle

I have two osgi bundles A and B. All packages of bundle A are private. In bundle B I used the code from https://stackoverflow.com/a/22800118/5057736:

BundleA

class ClassA extends ClassB{
ClassA(){
super(ClassA.class);
}
}


Bundle B

class ClassB{
...
public void doFoo(){
{
Bundle bundle = FrameworkUtil.getBundle(ClassAReference);
BundleWiring bundleWiring = bundle.adapt(BundleWiring.class);
// Getting all the class files (also from imported packages)
Collection<String> resources = bundleWiring.listResources("/", "*.class", BundleWiring.LISTRESOURCES_RECURSE);

List<String> classNamesOfCurrentBundle = new ArrayList<String>();
for (String resource : resources) {
URL localResource = bundle.getEntry(resource);
// Bundle.getEntry() returns null if the resource is not located in the specific bundle
if (localResource != null) {
String className = resource.replaceAll("/", ".");
classNamesOfCurrentBundle.add(className);
}
}


However, I get resources - all classes which bundle A classloader loaded. But I need only the classes which are inside bundle A. I mean I need classes which belong to bundle A. To get them as I understand I need localResource. However,localResource is always null, but the classes are exactly in bundle A - for example ClassA . How to get classes which belong to bundle A in ClassB?

Answer Source

Instead of

Collection<String> resources = bundleWiring.listResources("/", "*.class", BundleWiring.LISTRESOURCES_RECURSE);

use

List<URL> resources = bundleWiring.findEntries("/", "*.class", BundleWiring.FINDENTRIES_RECURSE);

The second function only looks for resources in the specific bundle and in its fragment bundles. See the javadoc: https://osgi.org/javadoc/r4v43/core/org/osgi/framework/wiring/BundleWiring.html#findEntries(java.lang.String,%20java.lang.String,%20int)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download