ClassCastException when converting from String to Object.. why?
Asked Answered
A

1

7

I am just playing with MessageFormat but when I try to pass a String to MessageFormat format method it compiles fine but then I get a runtime classcast exception. Here is the code.

MessageFormat format = new MessageFormat(""); Object obj = Integer.toHexString(10); format.format(obj);

Now the runtime exception I get is as follows.

Exception in thread "main" java.lang.ClassCastException: java.lang.String cannot be cast to [Ljava.lang.Object; at java.text.MessageFormat.format(Unknown Source) at java.text.Format.format(Unknown Source) at JavaCore2.Codepoint.main(Codepoint.java:21)

Assign answered 31/5, 2011 at 15:3 Comment(0)
H
6

MessageFormat.format() takes an argument of type Object[] (an Object array), whereas you are passing in a single Object.

You will have to create an array out of your Integer:

MessageFormat format = new MessageFormat("{0}");
Object[] args = { Integer.toHexString(10) };

String result = format.format(args);
Holmun answered 20/9, 2011 at 15:41 Comment(2)
This is correct answer javadoc clearly says that single argument format(obj) is equivalent to format(obj, new StringBuffer(), new FieldPosition(0)).toString(); which in turn(if you jump to another javadoc) is equivalent to format((Object[]) arguments, result, pos). What a nice people work in Oracle!Incorruption
Agreed. This gets me every time.Sajovich

© 2022 - 2024 — McMap. All rights reserved.