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. EasyUI 取得选中行数据

    转自:http://www.jeasyui.net/tutorial/23.html 本实例演示如何取得选中行数据. 数据网格(datagrid)组件包含两种方法来检索选中行数据: getSelect ...

  2. bzoj 1770: [Usaco2009 Nov]lights 燈【高斯消元+dfs】

    参考:https://blog.csdn.net/qq_34564984/article/details/53843777 可能背了假的板子-- 对于每个灯建立方程:与它相邻的灯的开关次数的异或和为1 ...

  3. 矩阵取数游戏 2007年NOIP全国联赛提高组(dp+高精)

    矩阵取数游戏 2007年NOIP全国联赛提高组  时间限制: 1 s  空间限制: 128000 KB  题目等级 : 黄金 Gold     题目描述 Description [问题描述]帅帅经常跟 ...

  4. python实现汉诺塔程序

    # 汉诺塔思想笔记# 认识汉诺塔的目标:把A柱子上的N个盘子移动到C柱子# 递归的思想就是把这个目标分解成三个子目标# 子目标1:将前n-1个盘子从a移动到b上# 子目标2:将最底下的最后一个盘子从a ...

  5. Akka源码分析-Akka-Streams-Materializer(1)

    本博客逐步分析Akka Streams的源码,当然必须循序渐进,且估计会分很多篇,毕竟Akka Streams还是比较复杂的. implicit val system = ActorSystem(&q ...

  6. 探寻宝藏 --- 双线DP

    双线DP , 在郑轻的时候 做过 这种双线DP  ,  这是多维DP 应该是比较简单的  但是那个 时间复杂度的优化 始终看不懂 .  先附上代码吧 , 等看懂了再来 , 补充一下 解释  . #in ...

  7. 最大化最小值poj2456Aggressive cows

    Aggressive cows Time Limit: 1000MS   Memory Limit: 65536K Total Submissions: 15528   Accepted: 7440 ...

  8. Windows 2008中部署dll到GAC

    两种方法: 1  gacutil.exe 2 直接拖动DLL到GAC (此种方式要关闭UAC,否则提示"Access is Denied")

  9. C语言指针的理解以及指针的指针的理解

    指针指向的是内存地址编号,内存地址编号指向的是对应的内容. 我们需要一个变量,来储存内存地址编号,这个变量的值是一个内存地址编号,但是我们可以通过修改变量的值,来不断的改变内存地址编号. 但是,我们如 ...

  10. Redux 中的CombineReducer的函数详解

    combineReducers(reducers) 随着应用变得复杂,需要对 reducer 函数 进行拆分,拆分后的每一块独立负责管理 state 的一部分. combineReducers 辅助函 ...