I want to read a value from the session object which returns Object type.
I know that the object has either true/false value.
I would like to convert that value into boolean type. So I have the following code.
session.getAttribute("MyKeyValue"); // It returns Object type
Below throws an Exception.
boolean myBoolVal = Boolean.parseBoolean((String) session.getAttribute("MyKeyValue"));
Below works properly.
boolean myBoolVal = Boolean.parseBoolean(session.getAttribute("MyKeyValue").toString());
Actually, I don't understand why option 1 is not working ?
When the runtime type of the instance returned by session.getAttribute("MyKeyValue") is not a String, casting it to String throws a ClassCastException.
On the other hand, session.getAttribute("MyKeyValue").toString() always works (assuming session.getAttribute("MyKeyValue") is not null), since all Objects have an implementation of the toString() method.
BTW, since session.getAttribute("MyKeyValue") doesn't return a String, it is likely that it returns a Boolean (since you expect Boolean.parseBoolean() to work), so if that is the case, instead of converting it to String and then to Boolean, you can just cast it to Boolean :
Boolean myBoolVal = (Boolean) session.getAttribute("MyKeyValue");
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