Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using varargs in a Tag Library Descriptor

Is it possible to have a TLD map to the following function:

public static <T> T[] toArray(T... stuff) {
    return stuff;
}

So that I can do:

<c:forEach items="${my:toArray('a', 'b', 'c')}"...

I tried the following <function-signature>s

java.lang.Object toArray( java.lang.Object... )
java.lang.Object[] toArray( java.lang.Object[] )

And others but nothing seems to work.

like image 880
Abdullah Jibaly Avatar asked Feb 17 '11 19:02

Abdullah Jibaly


2 Answers

Unfortunately that's not possible. The EL resolver immediately interprets the commas in the function as separate arguments without checking if there are any methods taking varargs. Your best bet is using JSTL fn:split() instead.

<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
...    
<c:forEach items="${fn:split('a,b,c', ',')}" var="item">
    ${item}<br/>
</c:forEach>

It would have been a nice feature in EL however, although implementing it would be pretty complex.

like image 170
BalusC Avatar answered Oct 06 '22 00:10

BalusC


oh well. so this is for literal construction, and there will be limited items

public static Object[] array(Object x0)
{ return  new Object[] {x0}; }

public static Object[] array(Object x0, Object x1)
{ return  new Object[] {x0, x1}; }

....

public static Object[] array(Object x0, Object x1, Object x2, ... Object x99)
{ return  new Object[] {x0, x1, x2, ... x99}; }

I don't find it sinful to do this. Auto generate 100 of them and you are set. Ha!

like image 30
irreputable Avatar answered Oct 05 '22 23:10

irreputable