Domanda

I have written a custom RequestWrapper to add cookies in to the request

    @Override
 public Cookie[] getCookies()
 {
         Cookie c=new Cookie("iPlanetDirectoryPro", "macleanpinto");
    Cookie c1=new Cookie("iPlanetDirectoryPro1", "macleanpinto1");

      Collection<Cookie> result = new ArrayList<Cookie>(2);

         result.add(c); 
         result.add(c1);
        return (Cookie[]) result.toArray();


 }

The above code at Return throws java.lang.ClassCastException. I am not able to be figure out why it does. Since i have created collection of cookies and i am trying return array list of cookies.

Thanks

È stato utile?

Soluzione

can you try result.toArray(new Cookie[2]); instead of (Cookie[]) result.toArray();?

Reason being - calling just result.toArray(); returns Object[]

If you see the source code of ArrayList

public Object[] toArray() {
    return Arrays.copyOf(elementData, size);
}

and

public <T> T[] toArray(T[] a) {
    if (a.length < size)
        // Make a new array of a's runtime type, but my contents:
        return (T[]) Arrays.copyOf(elementData, size, a.getClass());
System.arraycopy(elementData, 0, a, 0, size);
    if (a.length > size)
        a[size] = null;
    return a;
}

here the latter, clearly uses Arrays.copyOf passing the type of array

And Object[] can't be cast to Cookie[]

Altri suggerimenti

Try using ArrayList.toArray(T[] a).

Example:

return result.toArray(new Cookie[result.size()]);

As stated in the API, ArrayList.toArray() returns an array of type Object. Here's a thread explaining why you can't cast Object[] to String[]. Even though you're using Cookie[] the same principle applies.

ArrayList internally uses an Object[] to store the elements. So, when you use ArrayList#toArray() method, it returns the Object[].

Now, you cannot cast from an Object[] to a Cookie[], b'coz Object is not a subtype, but a supertype of Cookie. For example, consider below code:

Object[] objArray = {"a", 1, new Date()};    // an Object[]
Cookie[] cookieArray = (Cookie[]) objArray;  // You don't expect this to run

So, if you want an Cookie[], you have to iterate over the Object[] and manually convert each element to Cookie type, and add it to a new array. That is what ArrayList#toArray(T[]) does.

So, you can change your return statement to:

return result.toArray(new Cookie[result.size()]);

I've taken result.size() to avoid creation of an extra array in the method. You could have passed new Cookie[0] too. But, a new array will be created inside the toArray method.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top