Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)

like image 638
Adnan Bhatti Avatar asked May 31 '11 15:05

Adnan Bhatti


People also ask

Why do we get ClassCastException?

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.

How do you avoid ClassCastException?

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.

Which method throws ClassCastException?

A class cast exception is thrown by Java when you try to cast an Object of one data type to another.

Is ClassCastException checked or unchecked?

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.


1 Answers

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);
like image 51
andrewtc Avatar answered Sep 28 '22 22:09

andrewtc