1 post tagged “generics”
When doing J2EE development against Java5 a frequently encountered warning message is "The cast from X to Y is actually checking against the erased type Y." This is most frequently seen when getting a request or session attribute and putting it into a genericized collection:
List<MyObj> = (List<MyObj>) request.getAttribute(SOME_OBJ);
This constantly annoys me, so I came up with the following and put it in a helper class:
public static Collection<?> getAttributeAsTypedCollection(HttpServletRequest request, String attribute) {
Collection<Object> c = null;
Object obj = request.getAttribute(attribute);
if (null != obj && obj instanceof Collection) {
c = new ArrayList<Object>();
Collection<?> tmpList = (Collection<?>) obj;
c.addAll(tmpList);
}
return c;
}
Calling it with the following produces no warnings:
List<Integer> newList = (ArrayList<Integer>) getAttributeAsTypedCollection(request, "myAttr");