URLClassloader and ClassCastException
1 posts in topic
Flat View  Flat View
TOPIC ACTIONS:
 

Posted By:   Abhijit_Ambadkar
Posted On:   Monday, August 25, 2003 12:02 AM

Hi, We are looking at a requirement where we need to execute classes in a given classpath and use the output for further processing. We are using an Interface and a Abstract Factory. The Abstract Factory will instantiate classes which confirm to the Interface. We use a URLClassloader and load the Abstract Factory. Then get the instances by calling the factory method using reflection API. When we try to cast the object returned by the factory method we get a ClassCastException. We checked up the object being returned by the factory, there shouldnt be any ClassCastException. Has anyone faced such a situation? If so please let me kn   More>>

Hi,



We are looking at a requirement where we need to execute classes in a given classpath and use the output for further processing.



We are using an Interface and a Abstract Factory. The Abstract Factory will instantiate classes which confirm to the Interface.



We use a URLClassloader and load the Abstract Factory. Then get the instances by calling the factory method using reflection API.



When we try to cast the object returned by the factory method we get a ClassCastException.



We checked up the object being returned by the factory, there shouldnt be any ClassCastException.



Has anyone faced such a situation? If so please let me know what solution you used.



Thanks

Abhijit

   <<Less

Re: URLClassloader and ClassCastException

Posted By:   Darshan_Bildikar  
Posted On:   Monday, August 25, 2003 01:35 AM

Your problem is this. Say you have a factory class which gives you concrete instances of some implenting sub class.
This class has been loaded by a classloader different from the default one.

So if you have class B that extends abstract class A then the classloader stores exactly this info (dunno how)....

My guess is that you are trying to typecast the object returned to the interface (which of course if perfectly legal)... BUT... your current class loader does not yet have the information that the class of your current object actually implements your interface.. that information is stored only in your URL class loader...ur current classloader has only your interface loaded thus the cast fails.

A possible solution to this would be to explicitly load the class of your object using Class.forName or not use another classloader for loading your factory class.

Hope this helps
About | Sitemap | Contact