Thursday, January 29, 2009

java.lang.ClassCastException: [Ljava.lang.String; cannot be cast to java.lang.String When using HttpServletRequest getParameters()

I got the following error when trying to read a HttpServlet.getParameterMap(). Using the following code.

Map map=request.getParameterMap();
if(map.contains(key)){
String value=(String) map.get(key);
}


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

HttpServletRequest.getParameters() according to the javadocs returns an object of Map with the following attributes.

From the Java docs

"""
Returns:

an immutable java.util.Map containing parameter names as keys and parameter values as map values. The keys in the parameter map are of type String. The values in the parameter map are of type String array.
"""

So what it means is that it actually returns a type of Map<String,String[]> instead of Map<String,String>. So the correct defination is map.get(key) returns a String[] not a String. This is because request.getParameter(key) returns a String which is actually the first element of the resulting string array.

Have no idea why the designers design it this way. So to be safe, you can use the following to ensure that you will always use the correct type of map from a HttpServletRequest object.

Map<String,String[]> map=request.getParameterMap();

So read your javadocs carefully when you get weird ClassCastExceptions.

No comments:

Post a Comment