Amir.F
Amir.F

Reputation: 1961

Java Maven OSGi dynamic loading of jar from filesystem and running a class method from it at runtime

I have a NetBeans OSGi maven project that needs to run a class method from another OSGi jar which is loaded at runtime from the filesystem.

I tried looking at some of these similiar questions:

  1. Dynamic loading of modules in Java

  2. Loading of OSGi bundle dynamically from a file system

  3. Looking for basic example of using Apache Felix in dynamic loading of Jar file and instancing a class at runtime in Java

  4. java: is there a framework that allows dynamically loading and unloading of jars (but not osgi)?

  5. How to dynamically load Java classes at Runtime in OSGI framework?

but non of them seems to answer how I can access a method in the bundle I am loading.

they do seem to give me a good direction on how to load the bundle, but so does the documentation on OSGi. what i didn't find is how to run a specific method from a specific class in the bundle I installed. reflection does not seem to work and I have read that it might not be a good idea and in any case it gives me the famous ClassNotFoundException.

there is also the whole Manifest import and export as shown in this and other questions OSGi: programmitically add imports to a bundle

I cannot use bndtools, since I am using netbeans, also I'm not sure if it does the job. I am also not sure if OSGi services have anything to do with it.

Thanks in advance to anyone helping me not to pull my hair out :)

Upvotes: 1

Views: 1429

Answers (1)

Christian Schneider
Christian Schneider

Reputation: 19606

So I assume you already loaded and started the bundle. The next step is to get the classloader of the bundle:

ClassLoader loader = bundle.adapt(BundleWiring.class).getClassLoader();

Using this classloader you can load the class by name and use reflection to call the method on it.

Please also consider that this is not a good architecture for OSGi. If you know the other bundle and class already at compile time then simply use Import-Package and instantiate the other class with new.

If you do not know the other bundle and class at runtime but have control over all bundle sources then use a service approach. You could have a common interface shared by the bundles. The other bundle could offer its functionality as an OSGi service which you then can bind and access using the shared interface.

Upvotes: 3

Related Questions