Win a copy of OCP Java SE 8 Programmer II Exam Study Guide this week in the OCP forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Casting and Generics  RSS feed

 
Ranch Hand
Posts: 49
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Ranchers!

Could anyone remind me something about this generics-related warning?
My jdk is j2se 1.5.0_05.

While compiling the following row(option -Xlint).
Note: getJspContext() returns an Object.

ArrayList<MyImage> articlesList = (ArrayList<MyImage> getJspContext().getAttribute("imageList", PageContext.REQUEST_SCOPE);

this is the output:

src/it/infomedia/barry/EsempioSimpleTag/taghandlers/PicsTagHandler.java:44: warning: [unchecked] unchecked cast
found :java.lang.Object
required:java.util.ArrayList<it.infomedia.barry.EsempioSimpleTag.model.MyImage>
ArrayList<MyImage> articlesList = (ArrayList<MyImage> getJspContext().getAttribute("imageList",PageContext.REQUEST_SCOPE);

Why?

Thank you very much.

Regards,
Barry.
 
Ranch Hand
Posts: 580
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
getJspContext().getAttribute() returns an object which cannot directly assigned to ArrayList which is expecting only MyImage objects
 
Ranch Hand
Posts: 7729
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Basically it's saying "I'm accepting your cast, but I cannot guarantee that you are not going to get a ClassCastException at runtime if the type is not what you promise it is". It's not possible to fix all warnings like this if you have no access to the code for getJspContext().getAttribute(). But you can suppress the warning with an annotation - something like @SuppressWarnings("unchecked")
 
Barry Bassi
Ranch Hand
Posts: 49
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you very much Vidya and Barry!


Regards,
Barry.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!