I knew no error would occur, as I was setting the attribute in the HttpSession in the same servlet and I didn't want loads of warnings to build up, as this can hide real warnings I need to action.
So, my original code looked like
private void foo(HttpServletRequest request) {
HttpSession session = request.getSession(true);
List myItems = (ArrayList)session.getAttribute("myItems");
for (String myItem : myItems) {
...
HttpSession session = request.getSession(true);
List
for (String myItem : myItems) {
...
I found that to stop the error appearing you can suppress the warning, by adding the SupressWarnings command anywhere before the line that gives the warning.
private void foo(HttpServletRequest request) {
HttpSession session = request.getSession(true);
@SuppressWarnings("unchecked")
List myItems = (ArrayList)session.getAttribute("myItems");
for (String myItem : myItems) {
...
HttpSession session = request.getSession(true);
@SuppressWarnings("unchecked")
List
for (String myItem : myItems) {
...
Putting it just before the warning line, allows unexpected warnings before to still appear. But what about afterwards? In my case it wasn't necessary as the function had no more casts, but
private void foo(HttpServletRequest request) {
HttpSession session = request.getSession(true);
List myItems = null;
{
@SuppressWarnings("unchecked")
List uncheckedList = (ArrayList)session.getAttribute("myItems");
myItems = uncheckedList;
}
for (String myItem : myItems) {
...
HttpSession session = request.getSession(true);
List
{
@SuppressWarnings("unchecked")
List
myItems = uncheckedList;
}
for (String myItem : myItems) {
...
Placing the SuppressWarnings in brackets keeps the suppression inside, so any unexpected warnings afterwards will still appear.
I think it depends on your code as to if you need to go this far or just leave it as I did, with SuppressWarnings just before the warning line, or even place it at the top of the package.
Where is best... You Decide.
No comments:
Post a Comment