interface A
class B implements A
I am getting ClassCastException in casting B to A. Both A and B are in the same bundle.
This could be because of the class loader. Why is the class loader getting changed for the same bundle? How can I handle this problem?
Additional information
- interface A (ie AdminService) and the implementation class B (ie AdminServiceImpl) are in the same package (fusion-core)
- Whereas the casting is happening in a different package.
--The casting is not happening directly. ie
B b = new B(); A a = (A) b;is not happening. Casting is happening by resolving a service at OSGi service registry. ie
AdminService adminService = getService(AdminService.class.getName(), 100); public T getService(String type, long timeToWait) { ServiceTracker serviceTracker = serviceRegistry.get(type); if (serviceTracker == null) { serviceTracker = this.registerServiceTracker(type); } T service = null; try { service = (T) serviceTracker.waitForService(timeToWait); } catch (InterruptedException e) { logger.error("Error while fetching service", e); } return service; }
Epilog
Thank you Ivan, Angelo and BJ. Actually BJ's pointer helped me to fix the problem.
In the manifest of the bundle which was trying to perform the cast, <EXPORT-PACKAGE> was exporting the package of the other bundle which contained the interface and the implementation. Because of this probably the same byte code was getting loaded by the two different class loaders. Bundle (performing the cast) probably assumed the package to be a part of itself and loaded the byte code again !!!
Thanks a lot guys.