Narita
Narita

Reputation: 21

ClassCastException due to Class Loader problem

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


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.

Upvotes: 2

Views: 2663

Answers (1)

BJ Hargrave
BJ Hargrave

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

Related Questions