转自:https://www.jb51.net/article/198116.htm
python中的关键字占位符非常好用,但java并没有提供,发现网上有人写了一个,还挺好用
public class StringFormatUtil { private static final Pattern pattern = Pattern.compile("\{(.*?)\}"); private static Matcher matcher; public static String stringFormat(String sourStr, Map<String, Object> param) { String targetStr = sourStr; if (param == null) return targetStr; try { matcher = pattern.matcher(targetStr); while (matcher.find()) { String key = matcher.group(); String keyclone = key.substring(1, key.length() - 1).trim(); Object value = param.get(keyclone); if (value != null) targetStr = targetStr.replace(key, value.toString()); } }catch (Exception e){ e.printStackTrace(); } return targetStr; } public static String stringFormat(String sourStr, Object obj) { String targetStr = sourStr; matcher = pattern.matcher(targetStr); if (obj == null) return targetStr; PropertyDescriptor pd; Method getMethod; // 匹配{}中间的内容 包括括号 while (matcher.find()) { String key = matcher.group(); String keyClone = key.substring(1, key.length() - 1).trim(); try { pd = new PropertyDescriptor(keyClone, obj.getClass()); getMethod = pd.getReadMethod();// 获得get方法 Object value = getMethod.invoke(obj); if (value != null) targetStr = targetStr.replace(key, value.toString()); } catch (Exception e) { e.printStackTrace(); } } return targetStr; } public static void main(String[] args) { String template="select {column} from {table} " + "where tenant_code='{tenant_code}' " + "and bizmonth='{month}' " + "and bizyear='{month}'"; Map<String, Object> map = new HashMap<>(); map.put("column","a,b,c"); map.put("table","tableName"); map.put("tenant_code","0385"); map.put("month","2021-09"); String s = stringFormat(template, map); System.out.println(s); } }