Hello All,
Actually in my program I am casting userdefined class XYZ to String as
String mystr = myXYZ.toString();
where myXYZ is an object of type class XYZ, which gives no errors, and I send this string to an another program and in that program I am trying to retrieve the type XYZ from the String which I am not able to do, I am trying to do it similar to
Object myObject = (Object)new XYZ();
but getting an error
Invalid cast from java.lang.String to XYZ.
On the whole the things which I am doing are fine or am I doing something which shouldn't be done?
Please help me out.
Thanks
Sarada.
You were doing fine with
String mystr = myXYZ.toString();
Just implement the toString() method in the XYZ class
class XYZ {
int myInt;
public String toString() {
return "Hello, I am a XYZ with a value of "+myInt;
}
}
> Hello,
>
> So, how can I handle this case? How can I typecase a
>userdefined class to a String and vice-versa?
>
> Thanks,
> Sarada.
First, you should ask yourself WHY you really want to do this. But, if you absolutely had to, you could create your toString() method as said before that would list the values of ALL the attributes of that instance, and then you could create a static method in that class that would create an instance of that class based on the info in that String, but it is VERY sloppy code.
Tell us.. what exactly are you trying to do?
To be clear with what I am doing ,
I have a userdefined class with 3 attributes, and I want to create a session object with this class as a value, but as setSession() of HttpSession takes the String as a parameter, I want to convert my class to a String and pass it to setSession() of HttpSession and then convert back my string to my userdefined class when I retrieve the session object using getAttribute() of HttpSession. I guess this makes my question clear.
One more question, is it possible to set the value of a session with a userdefined object.
Thanks,
Sarada
There isn't any setSession() method in HttpSession. The method you want to use is setAttribute(String, Object) where the first parameter is a string that's used as a name for the object in the second parameter. So you don't need to convert your user-defined type to a string, you just put it in the second parameter of setAttribute.