Java 获取已在OSGi中注册的服务时发生ClassCastException
我最近开始研究OSGi框架。下面是我的TestingBundle jar中的类。下面是我针对该捆绑包的Activator类Java 获取已在OSGi中注册的服务时发生ClassCastException,java,osgi,classcastexception,apache-felix,osgi-bundle,Java,Osgi,Classcastexception,Apache Felix,Osgi Bundle,我最近开始研究OSGi框架。下面是我的TestingBundle jar中的类。下面是我针对该捆绑包的Activator类 public class Activator implements BundleActivator { private ServiceRegistration registration; @Override public void start(BundleContext context) throws Exception { r
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();
}
}
我不知道我到底做错了什么?有人能解释一下我在这里犯了什么错误吗?接口包,即
com.host.domain.app.modeling.framework
只能通过一个包导出。使用该包的所有其他捆绑包都应该导入它,而不是包含它们自己的副本
对此的解释是,在Java中,类的标识由该类的完全限定名和加载它的类加载器定义。如果您从多个捆绑包(以及多个类加载器)加载接口,则接口的每个副本都将被视为不同的、不兼容的接口。您尝试转换的对象已在不同的类加载器中创建,然后instanceof and casting不起作用。是的,看起来您是对的。。。你知道我该怎么解决这个问题吗?谢谢尼尔的建议。那么我该怎么办?你能为我提供解决这个问题的一步一步的建议吗?这意味着我应该改变什么,在哪里解决这个问题。谢谢你的帮助。@TechGeeky:请,请,在地下室挣扎之前,先掌握OSGi背后的概念:
SEVERE: Exception in App::initializeModel java.lang.ClassCastException: com.host.domain.app.modelling.framework.TestModelFramework incompatible with com.host.domain.app.modelling.framework.IModellingFramework