3

最近、OSGi フレームワークの作業を開始しました。以下は、TestingBundle jar にあるクラスです。以下は、そのバンドルの 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

ここで何が間違っているのかわかりませんか?ここで私が何をしたのか誰か説明してもらえますか?

4

1 に答える 1

4

インターフェイス パッケージ、つまり、 1 つのバンドルのみcom.host.domain.app.modelling.frameworkでエクスポートする必要があります。そのパッケージを使用する他のすべてのバンドルは、独自のコピーを含めるのではなく、それをインポートする必要があります。

これについての説明は、Java では、クラスの ID は、そのクラスの完全修飾名とそれをロードした ClassLoader によって定義されるということです。複数のバンドル (したがって複数の ClassLoader) からインターフェースをロードする場合、インターフェースの各コピーは異なる互換性のないインターフェースとして扱われます。

于 2013-08-18T23:06:53.380 に答える