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)
ClassCastException is a runtime exception raised in Java when we try to improperly cast a class from one type to another. It's thrown to indicate that the code has attempted to cast an object to a related class, but of which it is not an instance.
To prevent the ClassCastException exception, one should be careful when casting objects to a specific class or interface and ensure that the target type is a child of the source type, and that the actual object is an instance of that type.
A class cast exception is thrown by Java when you try to cast an Object of one data type to another.
ClassCastException is one of the unchecked exception in Java. It can occur in our program when we tried to convert an object of one class type into an object of another class type.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With