Crazymooner
Crazymooner

Reputation: 241

How to dynamically pass arguments for a java function using variable length parameter

Some function in java using variable length parameter. like

String java.lang.String.format(String format, Object... args)

How can dynamically pass parameter to this function?

For example

String fillInString(String str, ArrayList<String> token){
    return String.format(str, token[0], token[1]....);   
}

Upvotes: 0

Views: 7111

Answers (2)

Dave
Dave

Reputation: 888

send the token value to the function as an array.

String fillInString(String str, String ... token){
    return String.format(str, token);
}

var args like this can accept seperate arguments or an array.

Upvotes: 3

David Xu
David Xu

Reputation: 5597

String fillInString(String str, ArrayList<String> token){
    return String.format(str, token.toArray(new String[token.size()]));   
}

Upvotes: 3

Related Questions