我有一个捆绑组件,
package ipojo;
import ipojo.service.Hello;
import org.apache.felix.ipojo.annotations.Component;
import org.apache.felix.ipojo.annotations.Invalidate;
import org.apache.felix.ipojo.annotations.Provides;
import org.apache.felix.ipojo.annotations.Validate;
@Component(name="hello-factory")
@Provides
public class HelloImpl implements Hello{
@Override
public void shoutHello() {
System.out.println("HellooOOOOoooOooo!");
}
@Validate
public void start() throws Exception {
System.out.println("Hello started :)");
}
@Invalidate
public void stop() throws Exception {
System.out.println("Hello Stopped :(");
}
}在我的java应用程序中,我嵌入了Apache,并部署了iPOJO API。然后,我尝试使用Factory Service创建上述组件的实例,如下所示:
myBundle= context.installBundle("myBundlePath");
myBundle.start();
ServiceReference[] references = myBundle.getBundleContext().getServiceReferences(Factory.class.getName(), "(factory.name=hello-factory)");
if (references == null) {
System.out.println("No references!");
}
else {
System.out.println(references[0].toString());
Factory factory = myBundle.getBundleContext().getService(references[0]);
ComponentInstance instance= factory.createComponentInstance(null);
instance.start();
}我成功地获得了对工厂服务的引用,但在下面一行:
Factory factory = myBundle.getBundleContext().getService(references[0]);我得到以下ClassCastException:
java.lang.ClassCastException: org.apache.felix.ipojo.ComponentFactory cannot be cast to org.apache.felix.ipojo.Factory`我把这一行改为:
Factory factory = (ComponentFactory) myBundle.getBundleContext().getService(references[0]);然后我得到了:
java.lang.ClassCastException: org.apache.felix.ipojo.ComponentFactory cannot be cast to org.apache.felix.ipojo.ComponentFactory我该如何解决我的问题?谢谢。
发布于 2014-01-29 09:05:44
在嵌入Felix (或任何其他OSGi框架)时,您可以在类加载器之间创建一个边界。主机和包没有使用相同的类加载器,这意味着来自内部和外部的类不兼容。换句话说,从主机访问OSGi服务特别复杂,需要使用反射。
出于简单的原因,您应该使用来自包而不是主机的Factory服务(和任何其他服务)。
如果确实需要从主机上使用它们,则必须配置OSGi框架,以便从bundle 0导出所有必需的包。
发布于 2014-01-28 21:24:29
此异常意味着存在类路径问题,因为类路径中有多个版本的库。
当不能将类强制转换为同名类时,ClassCastException是由于尝试将类强制转换到类加载器而引起的:不可能这样做,请参阅here。
加载类的类加载器使类成为类唯一标识符的一部分。
因此,如果两个类在不同的类加载器中加载,那么两个名称完全相同的org.apache.felix.ipojo.ComponentFactory类将不是相同的。
您需要调试类路径,找到包含该类的库的不需要的版本并删除它。
https://stackoverflow.com/questions/21398859
复制相似问题