我最近开始研究 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
我不确定我在这里做错了什么?谁能解释我在这里做错了什么?