我必须生成一个包含类的所有数据成员的字符串。例如,如果一个类定义是
class A
{
private String field1;
private String field2;
private String field3;
...
...
}
然后我想生成一个按该顺序包含 field1、field2 和 field3 的字符串。但是,我想做的另一件事是确保以下规则 -
field1 is of length 20. If it is less than 20, pad it with blank spaces.
field2 is of length 10. If it is less than 10, pad it with blank spaces.
field1 is of length 15. If it is less than 15, pad it with blank spaces.
...
...
我计划使用一个帮助类来构建这个字符串。我想使用 StringBuilder 来获取最终的字符串。所以我有类似的东西 -
StringBuilder builder = new StringBuilder();
Helper.addString(field1,20,builder);
现在这个 addString 函数的实现是我关心的。对于不同的类,这个函数将被调用数千次。所以我想让它尽可能高效。问题是,最有效的方法是什么?目前,我有以下实现 -
public static void addString(String field, int totalLengthOfField, StringBuilder builder)
{
int lengthOfField = field.length();
int numberOfBlankSpacesToPutAfterString = totalLengthOfField - lengthOfField;
if(numberOfBlankSpacesToPutAfterString >=0)
{
builder.append(field);
for(int i=1; i<= numberOfBlankSpacesToPutAfterString; i++)
{
builder.append(" "); // append a blank space
}
}
else
{
// throw exception - field is longer than the maximum allowed length.
}
}