开发者

how to detect if running in osgi container

I have an OSGi bundle that can also run in plain Java process. I need to be able to tell if the bundle was loaded in an OSGi system or not. 开发者_高级运维How can I do that? If there is no OSGi-standard way of doing this, I will settle for Eclipse/Equinox-specific approach.


Add Bundle-Activator to your MANIFEST.MF. If it gets instantiated, then your JAR is running in an OSGi container.


If you don't have an activator, you can also try asking for your bundle:

Bundle b = org.osgi.framework.FrameworkUtil.getBundle(MyClass.this);

If it returns null, your class wasn't loaded by OSGi.


You can check whether "this.getClass().getClassLoader() instanceof org.osgi.framework.BundleReference", which should only be true if you are running in an R4.2 OSGi framework.


An improved answer to Richard S. Hall that doesn't require a compile and runtime dependency to osgi. It also checks if the classloader of a class implements org.osgi.framework.BundleReference interface.

Class<?> classToCheck = this.getClass().getClassLoader().getClass();
boolean runningOsgi = isOsgiClassLoader(classToCheck);
...

boolean isOsgiClassLoader(Class<?> classLoaderClass) {
    Class<?> c = classLoaderClass;
    while (c != null) {
        if (c.getName().equals("org.osgi.framework.BundleReference")) {
            return true;
        }
        for (Class<?> ifc : c.getInterfaces()) {
            if (isOsgiClassLoader(ifc)) {
                return true;
            }
        }
        c = c.getSuperclass();
    }
    return false;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜