Jim,
Thanks! You know, I thought that I had done class casting of arrays before, and I
also could have sworn that I did it within one of the methods of the MyCustomObject
class. But I just looked through all that code, and I bet that I *tried* it, it
failed, and I coded around it. But that's life at 3am in the Java fast lane ;)
Thanks for clueing me in to the Vector.toArray(array) method.
George
Jim Preston wrote:
> Ok, I think I've solved it. Here is your original sample code snippet:
>
> Vector myVec ;
> MyCustomObject mco = new MyCustomObject() ;
> myVec.add(mco) ;
> Object[] o = myVec.toArray() ;
> return (MyCustomObject)o ;
>
> This looks to me like the same problem that went by on this list a few weeks
> ago. It has nothing to do with being in a JSP. The problem is that you'll
> get a class cast exception on that return statement. Objects in Java "know"
> what they are, and you can't cast something to a type that it isn't. Arrays
> in Java are really just objects, whose type is array-of-<whatever>. the
> toArray method returns an object whose type is array-of-Objects. Even though
> each element of that array is, in fact, of type MyCustomObject, it does NOT
> follow that the array is automatically of type array-of-MyCustomObjects. An
> array is of whatever type it was created as, not array-of-<type of elements
> in the array>. So you can't cast an array whose type is array-of-Objects to
> the type array-of-MyCustomObjects, because the array just isn't of that
> type.
>
> This is the whole reason why there's a toArray method in the Vector class
> that takes an array as a parameter. That parameter is defined as an
> array-of-Objects, which means that you can actually pass in an array of any
> type (array-of-Objects is the superclass of every array type, just like
> Object is the superclass of every class; remember you can always cast up the
> superclass hierarachy, but above you're trying to cast down). Since the
> passed-in parameter "knows" what its actually type is, the method can create
> an array of THAT type rather than of type array-of-Objects. This array then,
> even though it's returned (as above) as a generic array-of-Objects will, in
> fact, be an array-of-MyCustomObjects, and the cast will therefore work. So,
> change the last two lines to the following, and it should work:
>
> MyCustomObject[] dummy = new MyCustomObject[0];
> MyCustomObject[] returnValue = (MyCustomObject[])myVec.toArray(dummy);
> return returnValue;
>
> --Jim Preston
===========================================================================
To unsubscribe: mailto [EMAIL PROTECTED] with body: "signoff JSP-INTEREST".
Some relevant FAQs on JSP/Servlets can be found at:
http://java.sun.com/products/jsp/faq.html
http://www.esperanto.org.nz/jsp/jspfaq.html
http://www.jguru.com/jguru/faq/faqpage.jsp?name=JSP
http://www.jguru.com/jguru/faq/faqpage.jsp?name=Servlets