Reputation: 1967
Im trying to access an osgi ds in a java project. I found an example like this on the internet:
BundleContext context = FrameworkUtil.getBundle(this.getClass()).getBundleContext();
ServiceReference serviceReference = context.getServiceReference(MyClass.class.getName());
MyClass blah = (MyClass) new ServiceTracker(context, serviceReference, null).getService();
blah.doStuff();
The problem here is that if i run this in a java class the "context" variable is null. I guess thats probably because its not in an osgi bundle.
I tried chaning things and it works if i change it like this:
BundleContext context = FrameworkUtil.getBundle(Myclass.class).getBundleContext();
But to be honest i really dont understand this bundle context. What exactly is it and can it be the same class that the reference class is?
Manual states the following: context - The BundleContext against which the tracking is done. ... but that doesent make things clearer for me.
Thanks!
Upvotes: 0
Views: 138
Reputation: 23948
FrameworkUtil.getBundle(Class)
only returns non-null if the class you pass in was loaded by an OSGi bundle classloader. That means you actually need to be in an OSGi bundle.
You need to be much clearer about what you're trying to do. "Accessing an OSGi DS in a Java project" is pretty much meaningless. Also since it seems you're just starting out with OSGi, why not start with something simple like working through a basic tutorial, rather than jumping in at the deep end?
Finally notice that the following code snippet is nonsense: MyClass.class.getClass()
. The literal MyClass.class
already gives you the class you want... if you then call getClass
on it you get the Class of java.lang.Class
! This is almost certainly not what you wanted.
Upvotes: 2