Created
June 11, 2014 21:02
-
-
Save kand/2762b3d930e802368629 to your computer and use it in GitHub Desktop.
In cases where there is no incoming request, you can retrieve a registered OSGi service through the current class' BundleContext. Provide ServiceUtil.getService() with the class of the service you wish to retrieve.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Methods for interacting with services. | |
*/ | |
public final class ServiceUtil { | |
private ServiceUtil() { | |
// private constructor for utility class | |
} | |
/** | |
* Get a service from the bundle context of given service class. | |
* | |
* @param serviceClass Class of service to retrieve from bundle context. | |
* @param <T> Type of service to retrieve. | |
* | |
* @return Requested service or null if it was not found. | |
*/ | |
public static <T> T getService(final Class<T> serviceClass) { | |
final BundleContext bundleContext = FrameworkUtil.getBundle(serviceClass).getBundleContext(); | |
final ServiceReference serviceReference = bundleContext.getServiceReference(serviceClass.getName()); | |
if (serviceReference != null) { | |
// return service class | |
return serviceClass.cast(bundleContext.getService(serviceReference)); | |
} else { | |
throw new IllegalArgumentException("No service registered for class " + serviceClass.getName()); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment