I understand t开发者_如何转开发hat the @SuppressWarnings("unchecked")
annotation can be used to suppress compiler warnings when generics aren't being used precisely as they're meant to be. And I understand that, from a purist perspective, one should almost never use these annotations and should just refactor the code so that there are no warnings.
But that got me thinking.
Are there any rules of thumb out there that dictate when it is safe to use these annotations (as opposed to "unsafe" uses that will result in debugging hell)? If so, what are they, and in what types of situations do they occur?
Thanks in advance!
If its your code and you know all the types which will be passed through that method, its not intrinsically "unsafe", as Java didn't always have generics - its more bad form. Its more an issue of whether you are sure that your code will work as you think it will work.
I pay as much attention to these issues as possible, but when using third-party libs, sometimes its just something you have to annotate to ignore. Example: Hibernates list()
method is unchecked, so Eclipse will complain. I know the objects I'm returning, so I can ignore it.
there are 2 major areas where i end up using this annotation frequently (and i would argue, correctly):
- dealing with third-party code which is not generified
- dealing with some external representation (e.g. serialization)
As mentioned above, the only real reason to add these is when you're using libraries from older versions of Java, or that simply don't use Generics. In this case, I usually choose to add the annotations, but I understand the arguments of those who don't.
Sometimes, it might not be possible to refactor the whole system to comply to the generics standard (it should, in a perfect world).
Other situation I've come across is when using generated code by some process, that doesn't generate generics... sometimes you can go and change the way the code is getting generated, sometimes you can't.
Anytime you can solve the problem without a SupressWarnings... do so! :D
The OCD in me chooses to seek out these and eliminate them to the max extent possible. The only reason I ever choose to live with these warnings is when I'm linking against a library that isn't using parametrized collections, iterators, classes, etc
However, I intentionally DO NOT add @SuppressWarnings so as I have a nice little hit list of issues that reminds me I need to do something about... when i have the time to rewrite external libs (or email the devs and make them do it :) )
"Effective Java 2nd Edition" has a very good discussion on the subject (chapter 5, item 25 and on):
http://books.google.com/books?id=ka2VUBqHiWkC&pg=PA117&lpg=PA117&dq=effective+java+@suppresswarnings+unchecked&source=bl&ots=yYDmPis6Q_&sig=YfF79nBl2fD79RRQIKNRg1WPUfs&hl=en&ei=FzWLTteZL6Ls0gHXmLn7BA&sa=X&oi=book_result&ct=result&resnum=1&ved=0CBoQ6AEwAA#v=onepage&q&f=false
精彩评论