只允许最后一个 Parameter 是可变长度:
String prepareStatement(String[] columnNames, String... values)
String... 等于 String[] 因此在这种情况下,您可以为第一个参数插入一个 String[] 并检查它是否为空或它有多长。
编辑到您的编辑
如果您确实需要将所有字符串作为参数输入,我建议您定义一个非常不常见的字符串来分隔您的输入:
static String prepareStatement(String... params)
{
String ret = "";
boolean valueInput = false;
for(String s : params)
{
if(s.equals("MyReallyUncommonSeperateString"))
{
valueInput = true;
ret+="\nvalues\n";//visual delimiter of columnNames and Values
}
else if(valueInput)
{
//handling of your value inputs
ret+=s; //example handling, concatenate everything
}
else
{
//handling of your columnnames
ret+=s; //example handling, concatenate everything
}
}
return ret;
}
你可以这样称呼它:
System.out.println(prepareStatement("a","b","c","d","e","MyReallyUncommonSeperateString","f","g","h","i","j","k"));
输出:
abcde
values
fghijk
另一种方法是将 columnNames 的长度也作为参数给出:
static String prepareStatement(int length, String... params)
{
String ret = "";
for(int i = 0; i < length; i++){
//handling of columnnames
String colName = params[i];
//do something with colName
ret+=colName; //example handling, concatenate everything
}
ret+="\nvalues\n";//visual delimiter of columnNames ans Values
for(int i = length; i < params.length; i++){
String value = params[i];
//do something with values
ret+=value; //example handling, concatenate everything
}
return ret;
}
随着电话:
System.out.println(prepareStatement(5, "a","b","c","d","e","f","g","h","i","j","k"));
同样的输出:
abcde
values
fghijk