Skip to content

Instantly share code, notes, and snippets.

@xcoulon
Created October 12, 2010 19:42
Show Gist options
  • Save xcoulon/622782 to your computer and use it in GitHub Desktop.
Save xcoulon/622782 to your computer and use it in GitHub Desktop.
package org.bytesparadise.tools.common.util;
import org.bytesparadise.tools.common.CommonBundleActivator;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;
/**
* A Bundle-scoped utility class for Declarative Services location.
*
* @author xcoulon
*
*/
//TODO : move to gist
public final class ServiceLocator {
/**
* Default private constructor.
*/
private ServiceLocator() {
}
/**
* Locate the Declarative Service that implements the given class.
*
* @param <T>
* the class type of the Declarative Service to locate
* @param clazz
* the Class of the Declarative Service to locate
* @return the located Declarative Service already casted in the type given
* in parameter
*/
@SuppressWarnings("unchecked")
public static <T> T locateService(final Class<T> clazz) {
Bundle bundle = CommonBundleActivator.getDefault().getBundle();
BundleContext context = bundle.getBundleContext();
// DS implements laziness transparently
// Obtain service reference
ServiceReference reference = context.getServiceReference(clazz
.getName());
if (reference == null) {
Logger.error("No reference found for service '"
+ clazz.getName()
+ "'. Check OSGI-INF/*.xml and MANIFEST.MF 'Service-Component' section");
return null;
}
// Obtain service instance
return (T) context.getService(reference);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment