Using varargs in a Tag Library Descriptor

后端 未结 4 1588
情话喂你
情话喂你 2021-01-11 17:18

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

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

So that I

相关标签:
4条回答
  • 2021-01-11 17:40

    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!

    0 讨论(0)
  • 2021-01-11 17:43

    It's a little more painful, but you could do something like this:

    class MyAddTag extends SimpleTagSupport {
        private String var;
        private Object value;
    
        public void doTag() {
            ((List) getJspContext().getAttribute(var).setValue(value);
        }
    }
    
    <my:add var="myCollection" value="${myObject}" />
    <my:add var="myCollection" value="${myOtherObject}" />
    <c:forEach items="myCollection">...</c:forEach>
    
    0 讨论(0)
  • 2021-01-11 17:43

    One thing I did to get around this was to create a utility function class and set it on the application context when the server starts up, rather than trying to define it as an EL function. You can then access the method in EL.

    So when my servlet starts up:

    context.setAttribute("utils", new MyJSPUtilsClass());

    and on my JSP:

    ${utils.toArray(1, 2, 3, 4)}

    0 讨论(0)
  • 2021-01-11 18:00

    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.

    0 讨论(0)
提交回复
热议问题