使用EL中的varargs调用方法引发java.lang.IllegalArgumentException:参数数量不正确。

7

我正在使用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)}

但是它给了我一个:

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

有没有一种方法可以从EL中执行这样的方法?

1个回答

16

不,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集合语法,无需使用整个EL函数。
#{[2,3,5].contains(OtherBean.category.id)}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接