'Request.getParameterMap values not castable to string'에 해당되는 글 1건

  1. 2013.08.06 Request.getParameterMap values not castable to string
01.JAVA/Java2013. 8. 6. 17:37
반응형

i am trying to get the complete parameter map from the request object and iterate over it.

here is the sample code

  Map map = request.getParameterMap();
for(Object key : map.keySet()){
    String keyStr = (String)key;
    Object value = map.get(keyStr);     
    System.out.println("Key " + (String)key + "     :    " + value);
}

output

  Key businessunit     :    [Ljava.lang.String;@388f8321
   Key site     :    [Ljava.lang.String;@55ea0889
  Key startDate     :    [Ljava.lang.String;@77d6866f
  Key submit     :    [Ljava.lang.String;@25141ee0
  Key traffictype     :    [Ljava.lang.String;@4bf71724

its evident from the output that the value object is an instance of String

now when i change my code to something like this

  Map map = request.getParameterMap();
  for(Object key : map.keySet()){
    String keyStr = (String)key;
    Object value = map.get(keyStr);
    if(value instanceof String)
    System.out.println("Key " + (String)key + "     :    " + (String)value);
}

it prints nothing but as per the previous output it should have printed the values and if i remove instanceOf check it gives ClassCastException. is this the expected behavior or i am doing something wrong here ?

share|improve this question
Three possibilities: 1. Did you redeclare class String somewhere (try using java.lang.String instead of String to find out)? 2. Are you using the exact same values when running the two pieces of code? 3. Try using String.valueOf(value) or value.toString() and see what happens. Hope it helps. – The Nail Dec 5 '11 at 7:34
Ah forget the above, it's an array. Fooled me. – The Nail Dec 5 '11 at 7:36
add comment (requires an account with 50 reputation)

[Ljava.lang.String;@XXXXXXX means it is array of String not a single String. So your condition fails and it does not print anything.

share|improve this answer
add comment (requires an account with 50 reputation)

The value is an array. If you're sure that the array is not empty, you should get the string value like this:

String value = (String) map.get(keyStr)[0];
share|improve this answer
add comment (requires an account with 50 reputation)

As the object which is returned is an array of strings as Harry Joy pointed out, you will have to use the Arrays.toString() method in order to convert that array to a printable string:

    Map map = request.getParameterMap();
    for (Object key: map.keySet())
    {
            String keyStr = (String)key;
            String[] value = (String[])map.get(keyStr);
            System.out.println("Key" + (String)key + "   :   " + Arrays.toString(value));
    }
share|improve this answer
Posted by 1010