是否有一个类似于sl4fj的通用stringreplace函数?
用sl4fj如果我想要构造一个string消息有一个很好的方法,利用替代。 例如,它可能是这样的:
logger.info("Action {} occured on object {}.", objectA.getAction(), objectB); 如果有多个replace需要,那么它是这样的: 
 logger.info("Action {} occured on object {} with outcome {}.", new Object[]{objectA.getAction(), objectB, outcome}); 
我的问题是:是否有一个通用的方式来创build一个string(而不仅仅是一个slf4j日志消息)? 就像是:
 String str = someMethod("Action {} occured on object {}.", objectA.getAction(), objectB); 
要么
 String str = someMethod("Action {} occured on object {} with outcome {}.", new Object[]{objectA.getAction(), objectB, outcome}); 
如果它在标准Java库中,那么“someMethod”是什么?
谢谢。
的String.format
 String str = String.format("Action %s occured on object %s.", objectA.getAction(), objectB); 
要么
 String str = String.format("Action %s occured on object %s with outcome %s.", new Object[]{objectA.getAction(), objectB, outcome}); 
您也可以使用数字位置来切换参数。
 String str = String.format("Action %2$s occured on object %1$s.", objectA.getAction(), objectB); 
您可以使用String.format或MessageFormat.format
例如,
 MessageFormat.format("A sample value {1} with a sample string {0}", new Object[] {"first", 1}); 
或干脆
 MessageFormat.format("A sample value {1} with a sample string {0}", "first", 1); 
如果您正在寻找一种解决scheme,您可以使用StrSubstitutorreplaceString中的一堆variables。
  Map<String, String> valuesMap = new HashMap<>(); valuesMap.put("animal", "quick brown fox"); valuesMap.put("target", "lazy dog"); String templateString = "The ${animal} jumped over the ${target}."; StrSubstitutor sub = new StrSubstitutor(valuesMap); String resolvedString = sub.replace(templateString); 
它遵循一个普遍接受的模式,在这个模式中,可以将带有variables的映射与未parsing的string一起传递给值,并返回已parsing的string。
我会build议使用org.slf4j.helpers.MessageFormatter 。 在它的帮助下,可以创build一个使用与slf4j完全相同的格式化风格的utillity方法:
 // utillity method to format like slf4j public static String format(String msg, Object... objs) { return MessageFormatter.arrayFormat(msg, objs).getMessage(); } // example usage public static void main(String[] args) { String msg = format("This msg is {} like slf{}j would do. {}", "formatted", 4, new Exception("Not substituted into the message")); // prints "This msg is formatted like slf4j would do. {}" System.out.println(msg); } 
  注意 :如果数组中的最后一个对象是一个exception,它将不会在消息中被replace,就像使用slf4jlogging器一样。 exception可以通过MessageFormatter.arrayFormat(msg, objs).getThrowable()来访问。