MessageFormat.format 字符串的模板替换

项目目前在消息的模版,模版中需要替换很多参数,比方说“用户名”,“日期”等等。不过目前没有想到更好的替换参数的方法,所以目前只能使用一个比较简单的方式来实现。
这个方式太死板,参数对应必须要在代码中写死,若是在模版中多加一个参数,那么就要修改Java类中的代码,非常不好。临时凑合一下,以后想到更好的方式,在来实现。
以下为代码实现: 其实这个实现就是使用了MessageFormat这个类; String content
= "ab,cc,{名称},{密码},{日期},dd,ff"; String array[] = {userName, password, format.format(new Date())}; content = MessageFormat.format(content, array);
解释如下: content 中需要被替换的就是{}中的参数,array数组中存放的是对应的要替换的参数;使用MessageFormat方法的时候,需要要将这些参数的个数匹配正确,
并且数序要指定,否则匹配出错。这样就实现了参数的替换。很简单,也很死板。 MessageFormat:出自java.text包中;

具体代码如下:

package org.xiaowu.json.demo;

import java.text.MessageFormat;

import org.junit.Test;

public class MessageFormatDemo {
    
    @Test
    public void Test(){
        StringBuilder sb=new StringBuilder();
        sb.append("    insert into test_tb (");
        sb.append("        createTime, ");
        sb.append("        datefrom, ");
        sb.append("        dateto, ");
        sb.append("        name, ");
        sb.append("        intranetid, ");
        sb.append("        actualhour, ");
        sb.append("        planhour, ");
        sb.append("        status");
        sb.append("    ) values (");
        sb.append("        ''{0}'',");
        sb.append("        ''{1}'',");
        sb.append("        ''{2}'',");
        sb.append("        ''{3}'',");
        sb.append("        ''{4}'',");
        sb.append("        ''{5}'',");
        sb.append("        ''{6}'',");
        sb.append("        ''{7}''");
        sb.append("    )");
        String result=sb.toString();
        
        Object[] arr={"20170520","王五","张三","李四","111","222","333","ok"};
        String sql=MessageFormat.format(result, arr);
        System.out.println("sql:"+sql);
    }
    
}

运行结果:

INSERT INTO test_tb (
    createTime,
    datefrom,
    dateto,
    NAME,
    intranetid,
    actualhour,
    planhour,
    STATUS
)
VALUES
    (
        '20170520',
        '王五',
        '张三',
        '李四',
        '111',
        '222',
        '333',
        'ok'
    )
原文地址:https://www.cnblogs.com/mr-wuxiansheng/p/6883361.html