Reputation: 21
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?
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;
}
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.
Upvotes: 2
Views: 2663
Reputation: 9384
If the code performing the cast to A has loaded a different A than the bundle which defined B (and contains A as you state), then there may be two different A classes in the VM. One from the bundle defining B and another one used by the bundle performing the cast to A.
Since A is a shared type, you need to make sure that the bundle defining B and the bundle casting to A are both using the same class A. They should both either import the package containing A from some 3rd bundle or the bundle defining B should export the package containing A so the bundle performing the cast to A can import that package.
Upvotes: 4