Invoke method with varargs in EL throws java.lang.IllegalArgumentException: wrong number of arguments
Asked Answered
P

1

7

I'm using JSF 2.

I have a method that checks for matching values from a list of values:

@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;
}


...
}

To call this method in EL I tried:

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

But it gave me a:

SEVERE [javax.enterprise.resource.webcontainer.jsf.context] (http-localhost/127.0.0.1:8080-5) java.lang.IllegalArgumentException: wrong number of arguments

Is there a way to execute such a method from EL?

Parish answered 22/3, 2013 at 0:14 Comment(0)
C
16

No, it is not possible to use variable arguments in EL method expressions, let alone EL functions.

Your best bet is to create multiple different named methods with a different amount of fixed arguments.

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) {}
// ...

As a dubious alternative, you could pass a commaseparated string and split it inside the method

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

or even a string array which is created by fn:split() on a commaseparated string

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

but either way, you'd still need to parse them as integer, or to convert the passed-in integer to string.

In case you're already on EL 3.0, you could also use the new EL 3.0 collection syntax without the need for the whole EL function.

#{[2,3,5].contains(OtherBean.category.id)}
Crisper answered 22/3, 2013 at 1:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.