Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
853 views
in Technique[技术] by (71.8m points)

jsf 2 - Invoke method with varargs in EL throws java.lang.IllegalArgumentException: wrong number of arguments

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...