MessageFormat简单使用

概述

在提示用户一些信息时,需要根据不同的情况在提示信息用说明具体情况,有很多文本内容的处理,为了避免大量使用 if 语句,使用java中对文本处理的工具 java.text.MessageFormat 。如果需要学习更多具体的使用方法,可以参考源代码或Oracle文档。

简介

格式化

对一组对象进行格式化处理,在合适的位置插入合适的参数,从而展现最终希望得到的消息。使用处理的格式:

MessageFormatPattern:
         String
         MessageFormatPattern FormatElement String

 FormatElement:
         { ArgumentIndex }
         { ArgumentIndex , FormatType }
         { ArgumentIndex , FormatType , FormatStyle }

 FormatType: one of 
         number date time choice

 FormatStyle:
         short
         medium
         long
         full
         integer
         currency
         percent
         SubformatPattern

示例

常用登陆功能,根据登陆的实际情况,返回不同的提示信息。

//提示主体内容
static final String message = "登陆处理,请确认:{0}!";

//提示类型
static String[] paraArray = new String[]{
        "登陆成功",
        "用户名或密码错误",
        "验证码错误",
        "异地登陆"
};

synchronized public String printMessage(int type) {
        String pushMsg = "";
        try {
            //文本主体,参数数组
            pushMsg = MessageFormat.format(message, paraArray[type]);
            
        } catch (Exception e) {
            System.out.println(e.getMessage());
            e.printStackTrace();
        }finally {
            if(StringUtils.isEmpty(pushMsg)){
                pushMsg="登陆请求处理失败,请重试或联系管理员!";
            }
        }
        return pushMsg;
    }

输出消息体:

登陆处理,请确认:用户名或密码错误!

你可能感兴趣的:(MessageFormat简单使用)