Search code examples
javaspringhttpclientapache-httpclient-4.xapache-commons-httpclient

FaultDescription:java.lang.ClassCastException - Error while casting HttpTemplate to CommonsHttpClient4XTemplate


Problem statement- Getting class castException while casting cbi.receptor.http.HttpTemplate template object to cbi.receptor.http.CommonsHttpClient4XTemplate

Overview- I am trying to type cast template object coming from cbi.receptor.http.HttpTemplate to cbi.receptor.http.CommonsHttpClient4XTemplate .Below is the piece of code from same.

ManageProxy.setProxy((CommonsHttpClient4XTemplate)template, dLogger, proxyFlag, proxyHost, proxyPort);

while casting it is throwing error i.e.

FaultDescription:java.lang.ClassCastException: com.sun.proxy.$Proxy21 cannot be cast to cbi.receptor.http.CommonsHttpClient4XTemplate

Debugging steps- When I am printing class classloader for template object I can see it is coming from default class loader sun.misc.Launcher$AppClassLoader@52cc8049 instead of cbi.receptor.http.HttpTemplate and that's why it is not getting casted as desired.

I have checked the required class files are present in my classpath .

Can anyone help me here to debug this issue as I am stuck from last two days only for this issue.Thanks in Advance.

Anshu


Solution

  • If I understand correctly, you want to type cast from one class to another, which may not be related and may not be possible. Type casting is intended to either broaden or narrow the scope of an object for a specific purpose. For example, I use type casting to save my class instances in objects to be saved to file. Then I re-cast them to the original scope for use after reading from file.

    Perhaps you could create a child class that can extend both classes. This should give you the flexibility to move data between the two or use the data from both. You just need to ensure you properly format the data to be transferred correctly. Does this help at all?