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);
}
public String get() {
return 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.
There's no such thing in Guava. You can have a look at SpEL (Spring Expression Language) which can do string templating, or other templating frameworks such as Velocity or Freemarker.
Yes, String.format().
String s = "Hey %s! Cool %s, right?";
System.out.println(String.format(s, "xybrek", "feature"));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With