ClassCastException when converting from String to Object.. why?
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)
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);
精彩评论