Created
October 12, 2010 19:42
-
-
Save xcoulon/622782 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
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