Replace field value(s) in a String
- by xybrek
Using Google Guava is there String utility to easily replace string field inside like this:
String query = mydb..sp_mySP ${userId}, ${groupId}, ${someOtherField}
Where I can do something like this:
StringUtil.setString(query)
.setField("userId", "123")
.setField("groupId", "456")
.setField("someOtherField", "12-12-12");
Then the resulting String would be:
mydb..sp_mySP 123, 456, 12-12-12
Of course, setting the String field patter like ${<field>} before the operation...
Anyway, this is my approach:
public class StringUtil {
public class FieldModifier {
private String s;
public FieldModifier(String s){
this.s = s;
}
public FieldModifier setField(String fieldName, Object fieldValue){
String value = String.valueOf(fieldValue);
s = modifyField(s, fieldName, value);
return new FieldModifier(s);
}
private String modifyField(String s, String fieldName, String fieldValue){
String modified = "";
return modified;
}
}
public FieldModifier parse(String s){
FieldModifier fm = new FieldModifier(s);
return fm;
}
}
So in this case, I just need to put the actual code in the modifyField function that will modify the string in a straightforward way. Also if there's a way so the parse function be static so I can just do StringUtil.parse(...) without doing new StringUtil().parse(...) which really doesn't look good.