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)方法的更多相关文章

  1. String.format(String format, Object... args)方法详解

    很多次见到同事使用这个方法,同时看到https://blog.csdn.net/qq_27298687/article/details/68921934这位仁兄写的非常仔细,我也记录一下,好加深印象. ...

  2. Java面试中hashCode()与equals(Object obj)方法关系的准确回答

    原文地址: https://blog.csdn.net/qq_19260029/article/details/77917925 hashCode()与equals(Object obj)都是Java ...

  3. C# IComparable接口、IComparer接口和CompareTo(Object x)方法、Compare()方法

    在项目中经常会用到字符串比较,但是有时候对字符串的操作比较多,规则各异.比如有的地方我们需要用排序规则,有的地方需要忽略大小写,我们该如何写一个比较容易操作的比较方法呢?重新实现IComparer接口 ...

  4. Class.isAssignableFrom(Class clz)与instanceof与Class.isInstance(Object obj) 的区别和联系

    编程的时候可能会遇到一个不知道它属于哪个类的对象,我们可以用下列运算符或者方法来判断.  1.instanceof instanceof是运算符只被用于对象引用变量,检查左边的被测试对象是不是右边类或 ...

  5. String.format(String format,Object... args)的用法

    String.format(String format, Object... args)方法详解 以前也看到过很多次这个用法,一直记不牢靠,今天整理一下.   我仅仅举几个例子稍做说明: String ...

  6. instanceof和isInstance(Object obj) 和isAssignableFrom(Class cls)的区别和联系

    instanceof和isInstance(Object obj) 和isAssignableFrom(Class cls)的区别和联系          编程的时候可能会遇到一个不知道它属于哪个类的 ...

  7. File类--System.out.print(Object obj)的理解

    一.File 类(java.io) 概述:Java中使用File类来表示文件或者文件夹对象!     抽象路径名:描述文件或文件夹时,使用的路径符号,就是一个对象的字符串表示形式,如"c:\ ...

  8. ArrayList集合--关于System.out.print(Object obj);的理解

    1.ArrayList集合中常用的方法 ArrayList<Student> stuArrayList = new ArrayList<>(); //定义一个集合对象 stuA ...

  9. 理解JAVA - 面向对象(object) - 属性,方法

    理解JAVA - 面向对象(object) - 属性,方法 多态的体现:    向上造型,父类接收子类对象:向上造型:    从父类角度看不到子类独有的方法:面向对象,人类认知世界的方式:生活中每天都 ...

随机推荐

  1. PCB 圆形板切边算法 实现

    在工程CAM处理圆形拼板是个头疼的问题,需人工程师自行设计切边 满足可以拼板并且拼板后锣板板边没有内角,不然会影响装配 1.原始单 PCS圆形板 此外形如果不采用邮票孔连接的话,采V-CUT连接须采用 ...

  2. linux vi 块操作、多窗口

    vim 块选择v:字符选择或者行选择[ctrl]+v: 块选择y:将反白的地方复制d:将反白的地方删除 多窗口:sp {filename} 打开一个新的窗口[ctrl]+w+j或者[ctrl]+w+向 ...

  3. c语言—栈区,堆区,全局区,文字常量区,程序代码区 详解

    转:http://www.cnblogs.com/xiaowenhui/p/4669684.html 一.预备知识—程序的内存分配 一个由C/C++编译的程序占用的内存分为以下几个部分1.栈区(sta ...

  4. 大数高精度加减乘除 51nod 1005 大数加法

    1005 大数加法 基准时间限制:1 秒 空间限制:131072 KB 分值: 0 难度:基础题  收藏  关注 给出2个大整数A,B,计算A+B的结果. Input 第1行:大数A 第2行:大数B ...

  5. 385 Mini Parser 迷你解析器

    Given a nested list of integers represented as a string, implement a parser to deserialize it.Each e ...

  6. 【转】mysql INSERT的用法

    转自:http://www.cnblogs.com/ggjucheng/archive/2012/11/05/2754938.html insert的语法 INSERT [LOW_PRIORITY | ...

  7. C#基础 结构体 枚举类型

    结构体:就是一个自定义的集合,里面可以放各种类型的元素,用法大体跟集合一样. 一.定义的例子: struct student { public int nianling; public int fen ...

  8. CDH搭建Hadoop分布式服务器集群(java新手小白)

    1首先对于一个java还白的小白,先理解CDH与Hadoop的关系 一.Hadoop版本选择. Hadoop大致可分为Apache Hadoop和第三方发行第三方发行版Hadoop,考虑到Hadoop ...

  9. HTTP的报文格式、GET和POST格式解析

    1. HTTP报文格式 HTTP报文是面向文本的,报文中的每一个字段都是一些ASCII码串,各个字段的长度是不确定的.HTTP有两类报文:请求报文和响应报文.请求报文一个HTTP请求报文由请求行(re ...

  10. 第四次团队作业——项目Alpha版本发布

    这个作业属于哪个课程  <课程的链接>         这个作业要求在哪里 <作业要求的链接> 团队名称 Three cobblers 这个作业的目标 发布项目α版本,对项目进 ...