4

Im using the following code to convert type object to string, fieldValue defined as is type object .

keyl.put(fieldName, (String) fieldValue);

the values of the type object can be only java types such as

java decimal ,byte,float, calendar ,date etc ...

when i got in fieldValue value of java.util.date I got an exception since the casting is not success. how can i overcome this issue?

6
  • 2
    If fieldValue is Object type then maybe instead of casting use fieldValue.toString(), or if it can be primitive type then String.valueOf(fieldValue). Commented Jun 19, 2013 at 15:36
  • If fieldValue is possibly null then String.valueOf(fieldValue) will prevent NullPointerException Commented Jun 19, 2013 at 15:38
  • @Pshemo Exactly :). OP gets an efficient answer,If he clarifies what is field-value. Commented Jun 19, 2013 at 15:42
  • @Baadshah true, that is why I only post comments :) Commented Jun 19, 2013 at 15:44
  • @Pshemo lol..got it ;). Commented Jun 19, 2013 at 15:45

2 Answers 2

5

If you want to get String representation of Object you can use fieldValue.toString() method. In case fieldValue can be primitive type (it wont have any methods) you can use String.valueOf(fieldValue).

Sign up to request clarification or add additional context in comments.

Comments

2

String is an Object but all the Objects are not Strings.

The cast can be to its own class type or to one of its subclass or superclass types or interfaces.

There are some rules of Object type casting in Java id it's a primitive type you can do

String.valueOf(fieldValue)

Comments

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.