MessageFormat.format用来格式化一个消息,通常是一个字符串。
例如:
String str = "{0},{1},{2}''{3}'','{4}'";
String b = MessageFormat.format(str, "1","2","3","4","5");
System.out.println(b);
输出:1,2,3'4',{4}
String getCodeUrl = "https://open.weixin.qq.com/connect/qrconnect?appid={0}&redirect_uri={1}&response_type=code&scope=snsapi_login&state={2}#wechat_redirect";
String appId = “11111”;
String redirectUri = “22222”;
String state = “OPEN”;
return MessageFormat.format(getCodeUrl, appId, redirectUri, state);
输出结果:https://open.weixin.qq.com/connect/qrconnect?appid=11111&redirect_uri=22222&response_type=code&scope=snsapi_login&state=OPEN#wechat_redirect
MessageFormat.format是根据顺序和占位符来插入的,1对应{0},2对应{1},3对应{2}。如果替换后需要加上单引号,像‘4’这样的,就需要在占位符上面对应加上两个单引号,这样才能准确转化为相应。如果加上一个单引号,结果就不会替换,最后输出是占位符本身{4}。
/**
* Creates a MessageFormat with the given pattern and uses it
* to format the given arguments. This is equivalent to
* <blockquote>
* <code>(new {@link #MessageFormat(String) MessageFormat}(pattern)).{@link #format(java.lang.Object[], java.lang.StringBuffer, java.text.FieldPosition) format}(arguments, new StringBuffer(), null).toString()</code>
* </blockquote>
*
* @param pattern the pattern string
* @param arguments object(s) to format
* @return the formatted string
* @exception IllegalArgumentException if the pattern is invalid,
* or if an argument in the <code>arguments</code> array
* is not of the type expected by the format element(s)
* that use it.
*/
public static String format(String pattern, Object ... arguments) {
MessageFormat temp = new MessageFormat(pattern);
return temp.format(arguments);
}
从源码中可以看出每调用一次MessageFormat.format就会实例化一次MessageFormat,实例化后只能使用一次,所以,如果要多次格式同一个模式的字符串,那么创建一个MessageFormat实例再执行格式化操作比较好:
String str = "{0},{1},{2}";
MessageFormat messageFormat = new MessageFormat(str);
String[] array = {"1","2","3"};
String c = messageFormat.format(array);
System.out.println(c);
输出:1,2,3