Jere Robinson wrote:
> Jere Robinson wrote:
> >
> > Hey guys, little 'ol me has been put on as head of my ISP's Java Servlet
> > shopping cart project. I have a question about the HttpSession method
> > getValue. It is supposed to return the object to which the String value
> > parameter (name) points, but when I try the following:
> >
> > cartitem A = new cartitem();
> > A.putName("Bar of Soap");
> > A.putPrice(150);
> > A.putQuantity(1);
> >
> > session.putValue(A.getName(),A);
> > cartitem B = new cartitem();
> > B = session.getValue(A.getName());
> >
> > It chokes on ' B = session.getValue(A.getName()); ' at compile time,
> > telling me I need to cast it:
> >
> > CartTest.java:31: Incompatible type for =. Explicit cast needed to
> > convert java.lang.Object to cartitem.
> > B = session.getValue(A.getName());
> > ^
> > What do I need to get this to work?
> > Oh, I need to overload the = operator in my cartitem class, don't I?
> > I'll send this in case I'm going down the wrong path. Even if I'm
> > right, how do we overload operators in Java?
> >
> > Thanks in advance!
> > Jere
You have to cast because the return value of HttpSession.getValue() is Object
-- you can store any object type that you like. Thus, change the line in
question to:
B = (cartitem) session.getValue(A.getName());
and it will compile fine. This causes the executing code to cast the return
value (an Object) into the type you want (a cartitem). It is no different
than extracting values from a Vector or a Hashtable, where the same issue
comes up.
Note: It is up to the developer to make sure that the cast you specify is
valid (in other words, that the object you stored under that name really can
be cast to the class or interface name you are using). Otherwise, you get a
ClassCastException at runtime on this line.
Craig McClanahan
___________________________________________________________________________
To unsubscribe, send email to [EMAIL PROTECTED] and include in the body
of the message "signoff SERVLET-INTEREST".
Archives: http://archives.java.sun.com/archives/servlet-interest.html
Resources: http://java.sun.com/products/servlet/external-resources.html
LISTSERV Help: http://www.lsoft.com/manuals/user/user.html