Eclipse正在向我发出以下形式的警告:
类型安全:从Object到HashMap的未选中转换
这是来自对我无法控制的API的调用返回Object:
HashMap<String, String> getItems(javax.servlet.http.HttpSession session) {
HashMap<String, String> theHash = (HashMap<String, String>)session.getAttribute("attributeKey");
return theHash;
}
Run Code Online (Sandbox Code Playgroud)
如果可能的话,我想避免Eclipse警告,因为理论上它们至少表明存在潜在的代码问题.但是,我还没有找到一种消除这种方法的好方法.我可以将涉及的单行提取到方法中并添加@SuppressWarnings("unchecked")到该方法,从而限制了我忽略警告的代码块的影响.有更好的选择吗?我不想在Eclipse中关闭这些警告.
在我来到代码之前,它更简单,但仍然引发了警告:
HashMap getItems(javax.servlet.http.HttpSession session) {
HashMap theHash = (HashMap)session.getAttribute("attributeKey");
return theHash;
}
Run Code Online (Sandbox Code Playgroud)
当您尝试使用哈希时,问题出在其他地方,您会收到警告:
HashMap items = getItems(session);
items.put("this", "that");
Type safety: The method put(Object, Object) belongs to the raw type HashMap. References to generic type HashMap<K,V> should be parameterized.
Run Code Online (Sandbox Code Playgroud) 我正在使用Jersey学习JAX-RS(又名JSR-311).我已经成功创建了一个Root资源并正在使用参数:
@Path("/hello")
public class HelloWorldResource {
@GET
@Produces("text/html")
public String get(
@QueryParam("name") String name,
@QueryParam("birthDate") Date birthDate) {
// Return a greeting with the name and age
}
}
Run Code Online (Sandbox Code Playgroud)
这很好用,并处理当前语言环境中的任何格式,日期(字符串)构造函数(如YYYY/mm/dd和mm/dd/YYYY)可以理解这种格式.但是,如果我提供的值无效或无法理解,我会得到404响应.
例如:
GET /hello?name=Mark&birthDate=X
404 Not Found
Run Code Online (Sandbox Code Playgroud)
我该如何自定义此行为?也许是一个不同的响应代码(可能是"400 Bad Request")?记录错误怎么样?也许在自定义标题中添加问题描述("错误日期格式")以帮助排除故障?或者返回包含详细信息的完整错误响应以及5xx状态代码?