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. Linux的文件搜索命令(locate ,find,grep,find命令和)

    刚开始学Linux,这是关于Linux文件搜索命令,就目前,尽我所能把他写全一点,后期随时补充 文件搜索命令 一.locate命令 二.find命令 三.grep命令 四.find命令和grep命令的 ...

  2. bzoj 1641: [Usaco2007 Nov]Cow Hurdles 奶牛跨栏【Floyd】

    先跑一遍取max版的Floyd,直接用数组回答询问即可 #include<iostream> #include<cstdio> using namespace std; con ...

  3. bzoj 1620: [Usaco2008 Nov]Time Management 时间管理【贪心】

    按s从大到小排序,逆推时间模拟工作 #include<iostream> #include<cstdio> #include<algorithm> using na ...

  4. Linux安装MySQL标准教程

    导读: 本文主要介绍 CentOS 系统二进制安装 MySQL 5.7.23 版本的安装步骤,其他版本安装过程相似. 1.前置准备 卸载旧版MySQL 查看rpm包 rpm -qa|grep mysq ...

  5. jQuery学习笔记(1)-初探

    一.jQuery是什么 1.jQuery是一套JavaScript脚本库,而不是框架:就好比"System是程序集"是类库,而"ASP.NET MVC"是框架: ...

  6. 关于java中replace的用法

    今天突然看到Java中的replace有两种方法,一种是直接替换,另一种是可以进行匹配替换的方式: public String replace(CharSequence target, CharSeq ...

  7. POJ_2828_Buy Tickets

    题意:插队问题: 2016.5.20,复习这道题. 总结:线段树基础不牢,建树,更新尚不熟悉,注意加强理解记忆. 主要理解:(单点更新,逆序插入) 发生插队时,前面的队伍是连续没有空位的,即pos:2 ...

  8. Application crashes -程序崩溃原因

    Typical errors that result in application crashes include: attempting to read or write memory that i ...

  9. Understanding and Analyzing Application Crash Reports

    Introduction When an application crashes, a crash report is created and stored on the device. Crash ...

  10. Python-Day07-图形用户界面和游戏开发

    Python-100Day-学习打卡Author: Seven_0507Date: 2019-05-22123 文章目录Python图形用户界面和游戏开发1. tkinter模块2. Pygame进行 ...