Search code examples
javajspjstlel

How to convert an arbitrary object to String with EL + JSTL? (calling toString())


Is there any way to call toString() on an object with the EL and JSTL? (I need the String representation of an enum as index in a map in a JSP EL expression.) I hoped something like ${''+object} would work like in java, but EL isn't that nice, and there does not seem to be any function that does it.

Clarification: I have a variable somemap that maps Strings to Strings, and I have a variable someenum that is an enumeration. I'd like to do something like ${somemap[someenum.toString()]}. (Of course .toString() does not work, but what does?)


Solution

  • You just do it like this:

    ${object}
    

    And it'll toString it for you.


    edit: Your nested expression can be resolved like this:

    <c:set var="myValue">${someenum}</c:set>
    ${somemap[myValue]}
    

    The first line stringifies (using toString()) the ${someenum} expression and stores it in the myValue variable. The second line uses myValue to index the map.