MessageFormat的用法

本文详细介绍了Java中的MessageFormat类,主要用于格式化字符串,特别是在错误处理和国际化中的应用。通过示例展示了如何使用format方法,以及遇到的问题如必须传入Object数组和避免类型转换异常。还对比了直接使用MessageFormat.format静态方法的简洁方式。
该文章已生成可运行项目,

简介

MessageFormat最广泛的用法是在字符串中用{}表示占位符进行填充,常用于错误处理国际化中。{0}表示后面传入参数的第一个参数

使用

  • format(Object obj)成员方法
   public static void testMessageFormat() {
        String object = "程序员职业生涯是{0}和{1}之间";
        MessageFormat format = new MessageFormat(object);
        String result = format.format(new String[]{"22", "33"});
        System.out.println(result);
   }

输出:

程序员职业生涯是22和33之间

注意,这里必须将参数放在一个数组中,且数组中的成员有toString()方法可以转换为String类型,即这里的数组不能是基本类型的数组,否则会报java.lang.ClassCastException:

    public static void testMessageFormat1() {
        String object = "程序员职业生涯是{0}和{1}之间";
        MessageFormat format = new MessageFormat(object);
        String result = format.format(new int[]{22, 33});
        System.out.println(result);
    }

输出

java.lang.ClassCastException: class [I cannot be cast to class [Ljava.lang.Object; ([I and [Ljava.lang.Object; are in module java.base of loader 'bootstrap')
  at line 885, java.base/java.text.MessageFormat.format
  at line 158, java.base/java.text.Format.format
  at line 25, Main.testMessageFormat1
  at line 5, Main.main

因为format()MessageFormat的抽象父类Format的方法,里面调用了抽象方法format(Object arguments, StringBuffer result, FieldPosition pos)

    /**
     * Formats an object to produce a string. This is equivalent to
     * <blockquote>
     * {@link #format(Object, StringBuffer, FieldPosition) format}<code>(obj,
     *         new StringBuffer(), new FieldPosition(0)).toString();</code>
     * </blockquote>
     *
     * @param obj    The object to format
     * @return       Formatted string.
     * @exception IllegalArgumentException if the Format cannot format the given
     *            object
     */
    public final String format (Object obj) {
        return format(obj, new StringBuffer(), new FieldPosition(0)).toString();
    }

MessageFormat实现了format(Object arguments, StringBuffer result, FieldPosition pos)方法,subformat()方法会将arguments强制转换为(Object[]),此时基本类型int[] 本身是一个object对象,不能转为obejct[],所以报ClassCastException。之后subformat()方法逐一判断是不是nullNumberDateString,如果都不是会尝试调用arg = obj.toString()方法。

    public final StringBuffer format(Object arguments, StringBuffer result,
                                     FieldPosition pos)
    {
        return subformat((Object[]) arguments, result, pos, null);
    }
    private StringBuffer subformat(Object[] arguments, StringBuffer result,
                                   FieldPosition fp, List<AttributedCharacterIterator> characterIterators) {
        // note: this implementation assumes a fast substring & index.
        // if this is not true, would be better to append chars one by one.
		// 忽略
         if (false) { // if (argRecursion == 3){
             // prevent loop!!!
             result.append('\uFFFD');
         } else {
             Object obj = arguments[argumentNumber];
             String arg = null;
             Format subFormatter = null;
             if (obj == null) {
                 arg = "null";
             } else if (formats[i] != null) {
                 subFormatter = formats[i];
                 if (subFormatter instanceof ChoiceFormat) {
                     arg = formats[i].format(obj);
                     if (arg.indexOf('{') >= 0) {
                         subFormatter = new MessageFormat(arg, locale);
                         obj = arguments;
                         arg = null;
                     }
                 }
             } else if (obj instanceof Number) {
                 // format number if can
                 subFormatter = NumberFormat.getInstance(locale);
             } else if (obj instanceof Date) {
                 // format a Date if can
                 subFormatter = DateFormat.getDateTimeInstance(
                          DateFormat.SHORT, DateFormat.SHORT, locale);//fix
             } else if (obj instanceof String) {
                 arg = (String) obj;

             } else {
                 arg = obj.toString();
                 if (arg == null) arg = "null";
             }
		// 忽略
        return result;
    }
  • MessageFormat.format(String pattern Object... arguments)静态方法
    public static void testMessageFormat2() {
        String object = "程序员职业生涯是{0}和{1}之间";
        String result = MessageFormat.format(object,22, 33);
        System.out.println(result);
    }

输出:

程序员职业生涯是22和33之间
本文章已经生成可运行项目
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Numb_昵称被抢了

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值