July 01, 2004
JSTL and instanceof

I'm working on a JSP page. I'm using JSTL's c:forEach to iterate through a collection, and I want to display each item.

Thing is, the collection is heterogeneous; that is to say, it contains objects of different types. Each object might be a String, in which case I want to show it as-is. It night be a Date, in which case I want to use JSTL's fmt:formatDate tag to format it for me. Lastly, it might be a BigDecimal which again I'll want to format, this time using fmt:formatNumber.

The question is, how can I tell what type of object I have? JSTL's EL seems to lack an instanceof operator. Will I have to write my own taglib for this?

Posted to Java by Simon Brunning at July 01, 2004 02:33 PM
Comments

I think you will have to write your own tag.
Or mix up your presentation and business logic and ensure everything is formatted as a String before it's put into the collection.

Posted by: Darren on July 1, 2004 04:12 PM

Are you using JSTL 1.0 (JSP 1.2) or JSTL 1.1 (JSP 2.0)? Neither one have a direct instanceof equivalent (although it is a reserved word in the EL), but there are different solutions possible if you're using JSTL 1.1/JSP 2.0.

Posted by: Kris Schneider on July 1, 2004 04:17 PM

The Apache Sandbox has a taglib that appears to do this, in their "Unstandard" tag library.

http://jakarta.apache.org/taglibs/sandbox/doc/unstandard-doc/intro.html

Failing that, I suppose you could do ${foo.class} or ${foo.class.name}, and compare against that, but obviously that is not the same as instanceof.

Posted by: Anonymous Coward on July 1, 2004 04:30 PM

I'm not building the collection, I'm afraid, Darren.

JSTL 1.0 for this project, Kris.

Oooh, ${foo.class.name} might just be good enough for my situation, AC. I'll give it a bash.

Thanks to all.

Posted by: Simon Brunning on July 1, 2004 04:49 PM

The easiest way to do this is ${foo.class.name}. Of course, you'll need to put in the full classname in your comparison test. This works well with the c:choose tag when you have a mumber of different typed objects to show.

Posted by: Pratik Patel on July 2, 2004 03:42 PM

If you using hibernate, it will create proxy and you can't use ${foo.class.name} directly....

Posted by: HoiKin on June 2, 2005 08:34 AM
Post a comment
Name:


Email Address:


URL:



Comments:


Remember info?