7

I'm using JSTL and want to check whether an object is a String or a Collection.

fn:length returns results on both types (stringsize or number of elements in the collection).

<c:if test="${fn:length(item)>1}">
   <c:out value="${fn:length(item)} " />
</c:if>

How can I determine which one I've got?

Hedge
  • 14,995
  • 36
  • 132
  • 233

3 Answers3

9

item.class lead to errors when using with tomcat 7. For me this works (although it's dirtier):

${item.link.getClass().simpleName == 'String'}
Matthias M
  • 10,450
  • 12
  • 78
  • 99
  • The accepted answer didn't work for me because of the newer version of Tomcat, but this did. Thank you! – Adam Konieska May 27 '16 at 14:33
  • This doesn't really work because what comes back for `getClass().simpleName` is **not** a String but `java.util.LinkedHashMap$Entry`. – gene b. Mar 12 '20 at 15:23
  • 1
    @gene: OP primarily wanted to check whether item is a String or something else. It works perfectly fine for the OP. – BalusC Mar 12 '20 at 15:55
9

You could look at the class name. For example:

<c:if test="${item.class.simpleName == 'String'}">
   <!-- it's a String! -->
</c:if>
dogbane
  • 254,755
  • 72
  • 386
  • 405
0

If you need to distinguish whether something is a Collection or not, you can use iteration to find out if it's a Collection, and set a var. This worked for me:

<c:set var="collection" value="false" />
<c:forEach var="item" items="${yourObjectWhichMayBeCollection}" varStatus="row">
    <c:if test="${row.index > 0}">
       <c:set var="collection" value="true" />
    </c:if>
</c:forEach>
<!--Now you can examine ${collection} & decide e.g. Collection vs. String -->
gene b.
  • 8,520
  • 12
  • 76
  • 167