背景
在MyEclipse2014环境下,使用JDK7.0时,在调用request.getParameterNames()给出了如下告警:
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
...
Enumeration<String> e = request.getHeaderNames();
...
}
Warning:
Type safety: the expression of type Enumeration needs unchecked conversion to conform to Enumeration<String>
问题原因排查
如果你去查询getHeaderNames()的帮助手册,可能会让你更加困惑,因为赋值操作两侧数据类型相同,确报出了上述错误信息。
Enumeration<String> getHeaderNames()
Returns an enumeration of all the header names this request contains. If the request has no headers, this method returns an empty enumeration.
Some servlet containers do not allow servlets to access headers using this method, in which case this method returns null
Returns:
an enumeration of all the header names sent with this request; if the request has no headers, an empty enumeration; if the servlet container does not allow servlets to use this method, null
此问题的原因在于从Servlet API 3.0(Java EE 6)开始,将此函数返回值进行了参数化处理。在一些老的版本像Servlet API 2.5(Java EE 5)及之前版本并没有将此函数参数。Servlet API 2.5中此函数的说明如下:
Enumeration getParameterNames()
Returns an Enumeration of String objects containing the names of the parameters contained in this request. If the request has no parameters, the method returns an empty Enumeration.
Returns:
an Enumeration of String objects, each String containing the name of a request parameter; or an empty Enumeration if the request has no parameters
很显然,你可能使用的是老的容器,可以查看web.xml进行确认。
<web-app version="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
......
</web-app>
解决方案
1. 将容器servlet版本升级到3.0,这样就可以使用下面的语句,而MyEclipse不会告警Enumeration<String> params = request.getParameterNames();
2. 使用unchecked转换
@SuppressWarnings("unchecked")
Enumeration<String> params = (Enumeration<String>) request.getParameterNames();