Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid unchecked-conversion-warning in Java, if you use legacy libraries?

I like the generics-feature in java and use it often. But I have a problem, if I use libraries that aren't yet aware of generics. An example are servlets. If you use ServletRequest.getParameterMap() the result will be a raw map, but it includes only String as keys and String[] as values. So I want to assign it to a Map<String, String[]>. But for this assignment I get an warning. How can I avoid this warning with the language, not by simply suppressing the warning with the @SuppressWarnings annotation.

like image 673
Mnementh Avatar asked Jul 15 '09 09:07

Mnementh


People also ask

How can I avoid unchecked cast warnings?

If we can't eliminate the “unchecked cast” warning and we're sure that the code provoking the warning is typesafe, we can suppress the warning using the SuppressWarnings(“unchecked”) annotation. When we use the @SuppressWarning(“unchecked”) annotation, we should always put it on the smallest scope possible.

What is unchecked conversion Java?

The warning message “unchecked conversion” implies that we should check the conversion before the assignment. To check the type conversion, we can go through the raw type collection and cast every element to our parameterized type.


2 Answers

As others have said the warnings cannot be avoided except by suppressing them. The issue IMHO is that either you have to litter your code with annotations that apply to small scope or ignore them globally and risk errors.

IIRC there is a proposal to generate warnings where the raw types are being returned instead of at the call.

Meanwhile, I think the best approach is to use a wrapper method so that the warnings are limited to a single place, where it is safe to ignore them:

class NoWarn {   public static Map<String, String[]> getParameterMap(ServletRequest r)    {     @SuppressWarnings("unchecked")     Map<String, String[]> result = r.getParameterMap();     return result;   } } 

Note This answer was edited with a comment that annotations cannot be inside method bodies. That is incorrect, the above is syntactically correct. I have reverted the change.

like image 91
Miserable Variable Avatar answered Oct 06 '22 10:10

Miserable Variable


The cleanest thing you can do is to encapsulate the conversion from legacy to generic code and suppress the warning only there.

E.g. you could put a generic facade on your legacy library, though this might not always be worthwhile.

like image 31
starblue Avatar answered Oct 06 '22 11:10

starblue