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. J20170602-ts

    アソシエーション association   n. 联想; 协会,社团; 联合,联系; アンケート    英文是questionnaire

  2. 疫情控制 2012年NOIP全国联赛提高组(二分答案+贪心)

    P1084 疫情控制 题目描述 H 国有 n 个城市,这 n 个城市用 n-1 条双向道路相互连通构成一棵树,1 号城市是首都,也是树中的根节点. H 国的首都爆发了一种危害性极高的传染病.当局为了控 ...

  3. 树形DP Codeforces Round #135 (Div. 2) D. Choosing Capital for Treeland

    题目传送门 /* 题意:求一个点为根节点,使得到其他所有点的距离最短,是有向边,反向的距离+1 树形DP:首先假设1为根节点,自下而上计算dp[1](根节点到其他点的距离),然后再从1开始,自上而下计 ...

  4. ViewPager(4)用viewpager实现splash view

    1,示例 2,代码 SplashMain.java import android.os.Bundle; import android.support.v4.app.Fragment; import a ...

  5. 漫谈未来的HDFS

    前面我们提到的HDFS,了解了HDFS的特性和架构.HDFS能够存储TB甚至PB规模的数据是有前提的,首先数据要以大文件为主,其次NameNode的内存要足够大.对HDFS有所了解的同学肯定都知道,N ...

  6. python与arduino串口通讯对接opencv实现智能物品分拣

    2018-05-0118:53:50 先上图: 再来视频: http://v.youku.com/v_show/id_XMzU3NzAwNzMyNA==.html?spm=a2hzp.8244740. ...

  7. windows服务器监控多个tomcat运行状态

     第一步,修改tomcat默认的进程名 因为所有的tomcat项目的进程名默认都叫java.exe,所以需要修改tomcat容器bin目录下的setclasspath.bat.注释掉:(在set前加上 ...

  8. Spartan6系列之GTP Transceiver的介绍与使用

    1.       什么是GTP transceiver? GTP transceiver是FPGA里一种线速度达500Mb/sà6.6Gb/s的收发器,利用FPGA内部可编程资源可对其进行灵活地配置, ...

  9. 如何在linux使用nmap端口扫描工具扫描网段内开放的端口

    在另一个linux主机上,使用nmap命令即可 ,比如 我在1.1.1.2上开放了端口1111 -A -j ACCEPT 在1.1.1.1上执行 即可查到

  10. CAD使用GetxDataLong读数据(网页版)

    主要用到函数说明: MxDrawEntity::GetxDataLong2 读取一个Long扩展数据,详细说明如下: 参数 说明 [in] LONG lItem 该值所在位置 [out, retval ...