简体   繁体   English

如何检测是否在osgi容器中运行

[英]how to detect if running in osgi container

I have an OSGi bundle that can also run in plain Java process.我有一个 OSGi 包,它也可以在普通的 Java 进程中运行。 I need to be able to tell if the bundle was loaded in an OSGi system or not.我需要能够判断捆绑包是否已加载到 OSGi 系统中。 How can I do that?我怎样才能做到这一点? If there is no OSGi-standard way of doing this, I will settle for Eclipse/Equinox-specific approach.如果没有执行此操作的 OSGi 标准方法,我将满足于 Eclipse/Equinox 特定的方法。

Add Bundle-Activator to your MANIFEST.MF.将 Bundle-Activator 添加到您的 MANIFEST.MF。 If it gets instantiated, then your JAR is running in an OSGi container.如果它被实例化,那么您的 JAR 正在 OSGi 容器中运行。

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.如果它返回 null,则 OSGi 未加载您的 class。

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.您可以检查“this.getClass().getClassLoader() instanceof org.osgi.framework.BundleReference”是否为 true,如果您在 R4.2 OSGi 框架中运行,则该选项应为 true。

An improved answer to Richard S. Hall that doesn't require a compile and runtime dependency to osgi.对 Richard S. Hall 的改进答案,它不需要 osgi 的编译和运行时依赖项。 It also checks if the classloader of a class implements org.osgi.framework.BundleReference interface.它还检查 class 的类加载器是否实现了org.osgi.framework.BundleReference接口。

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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM