获取已在OSGi中注册的服务时出现ClassCastException

时间:2013-08-18 20:35:33

标签: java osgi classcastexception apache-felix osgi-bundle

我最近开始研究OSGi框架。以下是我在TestingBundle jar中的类。下面是我的Bundle的Activator类。

public class Activator implements BundleActivator {

    private ServiceRegistration registration;

    @Override
    public void start(BundleContext context) throws Exception {

        registration = context.registerService(ITestFramework.class.getName(), new TestModelFramework(), null);

    }

    @Override
    public void stop(BundleContext context) throws Exception {


    }
}

以下是界面。

public interface ITestFramework {

    public void speak();

}

以下是实现上述接口的类

public class TestModelFramework implements ITestFramework {

    public TestModelFramework() {
    //
    }

    @Override
    public void speak() {

    System.out.println("Hello World");

    }

}

以下是我的主要应用程序代码,它将安装上述捆绑包,然后调用上述服务 -

private static Framework framework = null;

static {
    try {
        FileUtils.deleteDirectory(new File("felix-cache"));
        FrameworkFactory frameworkFactory = ServiceLoader.load(FrameworkFactory.class).iterator().next();

        framework = frameworkFactory.newFramework(new HashMap<String, String>());
        framework.start();
    } catch (IOException e) {
        LOG.log(Level.SEVERE, "Exception in App::static block " +e);
    } catch (BundleException e) {
        LOG.log(Level.SEVERE, "Exception in App::static block " +e);
    }       
}

public App() {

    installTheBundles(); //this method will install and start my above bundle
    initializeModel();
}

private static void initializeModel() {

    try {

    ServiceReference serviceReference = framework.getBundleContext().getServiceReference(ITestFramework.class.getName());

// this line throws me an exception         
TestModelFramework service = (TestModelFramework) framework.getBundleContext().getService(serviceReference);

    service.speak();

    } catch (Exception e) {
        LOG.log(Level.SEVERE, "Exception in App::initializeModel " +e);
        e.printStackTrace();
    }
}

}

以下是我经常遇到的例外情况 -

SEVERE: Exception in App::initializeModel java.lang.ClassCastException: com.host.domain.app.modelling.framework.TestModelFramework incompatible with com.host.domain.app.modelling.framework.IModellingFramework

我不确定我在这里做错了什么?谁能解释一下我在这里做了什么错?

1 个答案:

答案 0 :(得分:4)

接口包,即com.host.domain.app.modelling.framework必须由仅一个捆绑包导出。使用该软件包的所有其他软件包都应该导入它,而不是包含它们自己的副本。

对此的解释是,在Java中,类的标识由该类的完全限定名称加载它的ClassLoader定义。如果从多个bundle(以及多个ClassLoader)加载接口,那么接口的每个副本都将被视为不同的,不兼容的接口。