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)

1 Answer 1

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);
Sign up to request clarification or add additional context in comments.

2 Comments

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!
Agreed. This gets me every time.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.