Osgi 转换到接口期间的ClassCastException

Osgi 转换到接口期间的ClassCastException,osgi,glassfish-4,Osgi,Glassfish 4,我正试着玩OSGi,但我遇到了一个问题。。。 我有简单的类FirstVersionPrinter public class FirstVersionPrinter implements VersionPrinter { private final static String VERSION = "111"; @Override public String printVersion() { return VERSION; } } 和接口 public interface Ver

我正试着玩OSGi,但我遇到了一个问题。。。 我有简单的类FirstVersionPrinter

public class FirstVersionPrinter implements VersionPrinter {
private final static String VERSION = "111";

 @Override
 public String printVersion() {
     return VERSION;
 }
}
和接口

public interface VersionPrinter {
 public String printVersion();
}
和定位器类

@Override
public String print(Integer version) {

    final BundleContext bundleContext = FrameworkUtil.getBundle(getClass()).getBundleContext();
        for (Bundle bundle : bundleContext.getBundles()) {
            BundleContext bundleContext1 = bundle.getBundleContext();
                ServiceReference sr = bundleContext1.getServiceReference(VersionPrinter.class.getName());

            ...
(1)               ((VersionPrinter) bundleContext1.getService(sr)).printVersion());
在Locator中,我尝试遍历捆绑包并为我的VersionPrinter执行printVersion。但在第(1)行中,我得到了ClassCastException

java.lang.ClassCastException: example.FirstVersionPrinter cannot be cast to example.VersionPrinter
有人能解释一下为什么会这样吗? 谢谢


PS:Locator和FirstVersionPrinter位于不同的捆绑包中

如果多个捆绑包包含包示例,则始终会发生这种情况。如果“相同”类由两个不同的类加载器加载,那么java认为它不相同

因此,请确保理想情况下只有一个捆绑包中的接口类,并从那里导出它。需要该类的所有捆绑包都应导入此包

如果出于某种原因,您必须将示例包打包到多个包中,请确保所有这些包都在其清单中导入和导出包。这确保OSGi只选择一个包进行导出,并从所有其他包中导入


顺便说一句,您遍历bundle并向每个BundleContext请求服务引用的方式是不正确的。您只需使用一个BundleContext和do context.getServiceReferences即可获得所有FirstVersionPrinter服务。

example.VersionPrinter是否有可能在两个已安装的bundle中提供?如果你有OSGi控制台,你可以很容易地检查它。如果没有,您可以更改代码以检查是否有多个具有相同接口名称的服务以及它们来自哪个捆绑包。在console中只有一个捆绑包,但是在日志中,有许多来自不同包的ClassCastException,如“org.glassfish.main.admingui.console jms plugin”或“org.glassfish.main.connectors.admin”