【问题标题】:Invoke method with varargs in EL throws java.lang.IllegalArgumentException: wrong number of arguments在 EL 中使用可变参数调用方法会引发 java.lang.IllegalArgumentException:错误数量的参数
【发布时间】:2013-03-11 17:29:59
【问题描述】:

我正在使用 JSF 2。

我有一个方法可以检查值列表中的匹配值:

@ManagedBean(name="webUtilMB")
@ApplicationScoped
public class WebUtilManagedBean implements Serializable{ ...

public static boolean isValueIn(Integer value, Integer ... options){
    if(value != null){
        for(Integer option: options){
            if(option.equals(value)){
                return true;
            }
        }
    }
    return false;
}


...
}

我尝试在 EL 中调用此方法:

#{webUtilMB.isValueIn(OtherBean.category.id, 2,3,5)}

但它给了我一个:

严重 [javax.enterprise.resource.webcontainer.jsf.context] (http-localhost/127.0.0.1:8080-5) java.lang.IllegalArgumentException: 参数数量错误

有没有办法从 EL 执行这样的方法?

【问题讨论】:

    标签: jsf-2 el


    【解决方案1】:

    不,不能在 EL 方法表达式中使用可变参数,更不用说 EL 函数了。

    最好的办法是创建多个具有不同数量的固定参数的不同命名方法。

    public static boolean isValueIn2(Integer value, Integer option1, Integer option2) {}
    public static boolean isValueIn3(Integer value, Integer option1, Integer option2, Integer option3) {}
    public static boolean isValueIn4(Integer value, Integer option1, Integer option2, Integer option3, Integer option4) {}
    // ...
    

    作为一个可疑的替代方案,您可以传递一个逗号分隔的字符串并将其拆分到方法中

    #{webUtilMB.isValueIn(OtherBean.category.id, '2,3,5')}
    

    甚至是由fn:split()在逗号分隔的字符串上创建的字符串数组

    #{webUtilMB.isValueIn(OtherBean.category.id, fn:split('2,3,5', ','))}
    

    但无论哪种方式,您仍然需要将它们解析为整数,或者将传入的整数转换为字符串。

    如果您已经使用 EL 3.0,您也可以使用新的 EL 3.0 collection syntax 而无需整个 EL 功能。

    #{[2,3,5].contains(OtherBean.category.id)}
    

    【讨论】:

      猜你喜欢
      • 2011-03-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多