Alfred’s Computing Weblog

Alfred Java-cored Computing Weblog

Java | ERROR: java.lang.ClassCastException: [Ljava.lang.String; cannot be cast to java.lang.String

leave a comment »

ERROR: java.lang.ClassCastException: [Ljava.lang.String; cannot be cast to java.lang.String

Story:
Ok, I hits the above error when I try to loop through the request parameters, and print out all parameter Key and Value.
The ClassCastException is a general exception, it will be thrown when you try to cast an Apple to an Orange. Thats simple!
When the first time I read this exception message, “[Ljava.lang.String; cannot be cast to java.lang.String”, I though there is some typo in the compiler 😛
What is the difference between “[Ljava.lang.String” and “java.lang.String”?
From the wording itself, quite straight forward. The later do not have “[L”, but what is the “[L”?
Thanks for some stupid errors I hit before, I recall that the “[L” is the representation of Array object!

CODE / SOLUTION:
Here is the way I used to print out all parameter Key and Value. I’m not sure its a correct / best way, but its works!

Map paramMap = request.getParameterMap();
Iterator iter = paramMap.entrySet().iterator();
while(iter.hasNext()) {
    Entry<String, String[]> entry =  (Entry<String, String[]>) iter.next();
    String key = entry.getKey();
    String value = entry.getValue()[0];
    logger.debug("key[{}] value[{}]", key, value);
}

Written by Alfred

June 22, 2010 at 20:08

Posted in Java

Tagged with , , ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: