Should I add try/catch around when casting on an attribute of JSP implicit object?
Posted
by Michael Mao
on Stack Overflow
See other posts from Stack Overflow
or by Michael Mao
Published on 2010-06-13T11:10:54Z
Indexed on
2010/06/13
11:22 UTC
Read the original article
Hit count: 271
Hi all:
Basically what I mean is like this:
List<String[]> routes = (List<String[]>)application.getAttribute("routes");
For the above code, it tries to get an attribute named "routes" from the JSP implicit object - application. But as everyone knows, after this line of code, routes may very well contains a null - which means this application hasn't got an attribute named "routes".
Is this "casting on null" good programming practice in Java or not?
Basically I try to avoid exceptions such as java.io.InvalidCastException
I reckon things like this are more as "heritage" of Java 1.4 when generic types were not introduced to this language. So I guess everything stored in application attributes as Objects (Similar to traditional ArrayList). And when you do "downcast", there might be invalid casts.
What would you do in this case?
Update:
Just found that although in the implicit object application I did store a List of String arrays, when I do this :
List<double[]> routes = (List<double[]>)application.getAttribute("routes");
It doesn't produce any error... And I felt not comfortable already...
And even with this code:
out.print(routes.get(0));
It does print out something strange :
[Ljava.lang.String;@18b352f
Am I printing a "pointer to String"? I can finally get an exception like this:
out.print(routes.get(0)[1]);
with error :
java.lang.ClassCastException: [Ljava.lang.String;
Because it was me to add the application attribute, I know which type should it be cast to. I feel this is not "good enough", what if I forget the exact type? I know there are still some cases where this sort of thing would happen, such as in JSP/Servlet when you do casting on session attributes. Is there a better way to do this?
Before you say:"OMG, why you don't use Servlets???", I should justify my reason as this: - because my uni sucks, its server can only work with Servlets generated by JSP, and I don't really want to learn how to fix issues like that. look at my previous question on this , and this is uni homework, so I've got no other choice, forget all about war, WEB-INF,etc, but "code everything directly into JSP" - because the professors do that too. :)
© Stack Overflow or respective owner