ClassCastException when converting from String to Object .. why?

I just play with MessageFormat , but when I try to pass the String method to MessageFormat format , it compiles fine, but then I get a class exception. Here is the code.

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

Now I get an exception at runtime:

An exception in the "main" thread java.lang.ClassCastException: java.lang.String cannot be passed to [Ljava.lang.Object; in java.text.MessageFormat.format (Unknown source) in java.text.Format.format (Unknown source) in JavaCore2.Codepoint.main (Codepoint.java21)

+6
source share
1 answer

MessageFormat.format() takes an argument of type Object[] (an array of Object ), while you are passing one Object .

You will need to create an array from Integer :

 MessageFormat format = new MessageFormat("{0}"); Object[] args = { Integer.toHexString(10) }; String result = format.format(args); 
+6
source

Source: https://habr.com/ru/post/889461/


All Articles