In your situation I use a solution similarto that suggested by Ryan Stewart, but I prefer Google Guava instead of Apache Commons. I prefer this library because I feel that Apache libraries are to gigantic and interlinked.
Here below is how I would build your SQL string:
import com.google.common.base.Joiner;
import com.google.common.collect.Lists;
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import java.util.List;
public class SqlJoiner {
public String buildSql(
boolean addOpen,
boolean addHigh,
boolean addLow,
boolean addSettle,
String tableName
) {
Preconditions.checkArgument(!Strings.isNullOrEmpty(tableName));
Preconditions.checkArgument(addOpen | addHigh | addLow | addSettle );
final List<String> clauses = Lists.newArrayList();
if (addOpen) clauses.add("Open");
if (addHigh) clauses.add("High");
if (addLow) clauses.add("Low");
if (addSettle) clauses.add("Settle");
StringBuilder builder = new StringBuilder();
builder.append("SELECT ");
builder.append(Joiner.on( , ).join(clauses));
builder.append(" FROM " + tableName);
return builder.toString();
}
}
方法正文起始处的先决条件是要确定至少一个布林选项总是真实的, 而该表名不是空的或空的。 总是检查您的代码的前提条件, 当您将来使用代码出错时, 它会省下很多麻烦!