Reputation: 545
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 ?
Upvotes: 4
Views: 1098
Reputation: 36401
You can set in the session object any object you want and associate to it a key. Any object means any object of any class. As any class is a possibly indirect sub class of Object
then type is Object
in set
and get
.
When you retrieve an object via get
it is simply typed as Object
but is certainly of some subclass. (Down)casting it to String
may fails (an exception is thrown saying that the cast/conversion can't be realized) if the original class is not String
. Seems to be the case for your option 1.
Option 2 works because any Object
instance has a method toString()
that can be called to get a String
representation of the object (mainly useful for onscreen presentation of it). Then you parse
that representation (probably "true"
or "false"
) to obtain a boolean
of value true
or false
.
So if you want your option 1 to work, as your object is probably a Boolean
instance, you can use:
boolean myBoolVal = (Boolean)session.getAttribute("MyKeyValue");
Upvotes: 0
Reputation: 393846
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");
Upvotes: 8