I have am using a framework which has a cache object which allows you to store String, Object pairs. I want to store a custom object, lets say Cow. I read another message here which says you cannot downcast, such as (Cow) Animal. Why then does (String) Object work? Is there a way I can restore my Object to a Cow?
Yes. You can downcast (Cow)Animal. As long as the Animal is also a Cow. You can store the Cow as <CODE>Object</CODE> with String key "MyCow". Then retrieve it with Cow myCow = (Cow)hashTable.get("MyCow");
Tony Alicea Senior Java Web Application Developer, SCPJ2, SCWCD
It's not really that you can't downcast - it's that you can't turn an object into something it's not by downcasting. That will give you runtime problems. Here's an example:-
If you compile this code, it compiles without a problem. But when you run it, it falls over as it attempts the first cast. If you comment out the first cast, it compiles and runs fine. myArray is an array of objects and what you add to it must be instances of Object or instances of Object's subclasses. When you're dealing with members of myArray, you can treat them like objects. But that doesn't change what they are. So the first member remains an Object and the second member is a String - so it's fine to downcast the second member because it really is a string. But you can't cast myArray to a String because it's an Object and it's missing some of the things it would need to be a String (for example, it doesn't have an over-ridden equals() method). It won't fall over until runtime because of late binding - Java doesn't actually work out what type of object we're really dealing with until runtime. So if you know what you're actually dealing with is a Cow (you can check using the instanceof operator), it's fine to do the downcast (Cow) Animal. Hope this helps, Kathy
I am saving this to a cache which accepts a key value (String) and an Object. The Object I am passing in is of type cow. cache.putObjectInCache("Cow", Cow); When I create an instance of the cache elsewhere, and try to get the Object with the key, casting it to type Cow, I get a class cast exception. Cow newcow = (Cow) cache.getObjectFromCache("Cow"); So, I shoudl nto be getting an eror, since I know it is of type cow? I tried Object newcow = cache.getObjectFromCache("Cow"); newcow.toString() and get info that the object came from the cow package.
The problem I was having is that I am using SilverStream and had two instances of Cow, one in the Object Designer and one in a jar file. The one class was being used to create the Cow object, and the other to cast. They did not match so I had issues. Thanks for your help!