1. 程式人生 > >MessageFormat理解,MessageFormat.format(Object obj)方法

MessageFormat理解,MessageFormat.format(Object obj)方法

his HR rri n) can alignment lan this ringbuf

MessageFormat.format(Object obj)方法主要用途為拼接message信息

用法:

Object[] testArgs = {new String("張三"),new String("大傻子")};

MessageFormat form = new MessageFormat("{0}是個{1}");

String format = form.format(testArgs);

System.out.println(format);

輸出結果:

張三是個大傻子

疑問一:format(testArgs);這裏傳的參數為Object[]類型

源碼為:

/**
     * 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(); }

這裏要求參數為Object類型,嘗試傳Object類型,代碼如下:

public static void main(String[] args) {
         //Object[] testArgs = {new String("張三"),new String("大傻子")};
         Object testArgs1 = new
String("張三"); MessageFormat form = new MessageFormat("{0}是個大傻子"); String format = form.format(testArgs1); System.out.println(format); }

報錯<java.lang.ClassCastException>信息如下

Exception in thread "main" java.lang.ClassCastException: java.lang.String cannot be cast to [Ljava.lang.Object;
    at java.text.MessageFormat.format(MessageFormat.java:865)
    at java.text.Format.format(Format.java:157)
    at lijian.test.Test000.main(Test000.java:14)

深入源碼分析:

Format中的format (Object obj)實際return的為

format(obj, new StringBuffer(), new FieldPosition(0)).toString();

找到這個方法

/**
     * Formats an object and appends the resulting text to a given string
     * buffer.
     * If the <code>pos</code> argument identifies a field used by the format,
     * then its indices are set to the beginning and end of the first such
     * field encountered.
     *
     * @param obj    The object to format
     * @param toAppendTo    where the text is to be appended
     * @param pos    A <code>FieldPosition</code> identifying a field
     *               in the formatted text
     * @return       the string buffer passed in as <code>toAppendTo</code>,
     *               with formatted text appended
     * @exception NullPointerException if <code>toAppendTo</code> or
     *            <code>pos</code> is null
     * @exception IllegalArgumentException if the Format cannot format the given
     *            object
     */
    public abstract StringBuffer format(Object obj,
                    StringBuffer toAppendTo,
                    FieldPosition pos);

是一個抽象方法,由於是MessageFormat調用的,所以在MessageFormat類中找其實現方法

// Overrides
    /**
     * Formats an array of objects and appends the <code>MessageFormat</code>‘s
     * pattern, with format elements replaced by the formatted objects, to the
     * provided <code>StringBuffer</code>.
     * This is equivalent to
     * <blockquote>
     *     <code>{@link #format(java.lang.Object[], java.lang.StringBuffer, java.text.FieldPosition) format}((Object[]) arguments, result, pos)</code>
     * </blockquote>
     *
     * @param arguments an array of objects to be formatted and substituted.
     * @param result where text is appended.
     * @param pos On input: an alignment field, if desired.
     *            On output: the offsets of the alignment field.
     * @exception IllegalArgumentException if an argument in the
     *            <code>arguments</code> array is not of the type
     *            expected by the format element(s) that use it.
     */
    public final StringBuffer format(Object arguments, StringBuffer result,
                                     FieldPosition pos)
    {
        return subformat((Object[]) arguments, result, pos, null);
    }

這裏對arguments參數做了一個強轉...強轉為了Object[]方法,怪不得報錯了

由於業務需要,這裏必須傳Object,而不能傳數組,這如何解決?

掩耳盜鈴方案:

public static void main(String[] args) {
         Object[] testArgs = {new String("張三"),new String("大傻子")};
         Object testArgs1 = testArgs;

         MessageFormat form = new MessageFormat("{0}是個{1}");
         
         String format = form.format(testArgs1);

         System.out.println(format);
        
        
    }

將Object[]數組轉為Object類型,誰讓它是根類呢,啥都能裝

到MessageFormat類中的format方法時強轉回Object[]數組,就不會報錯了

運行結果:

你是個大傻子

MessageFormat理解,MessageFormat.format(Object obj)方法