【发布时间】:2014-11-17 16:16:16
【问题描述】:
SqlOutParameter out = new SqlOutParameter("out_refcursor",OracleTypes.CURSOR
,new StudentRowMapper());
// 一些代码..
MapSqlParameterSource parameters = createMapSqlParameterSource();
parameters.addValue("in_studentid","101");
Map<String, Object> result = simpleJdbcCall.execute(parameters);
List<Student> students = (List<Student>) result.get("out_refcursor"); // here I get a warning
execute()方法的定义:
Map<String, Object> org.springframework.jdbc.core.simple.SimpleJdbcCall.execute(SqlParameterSource parameterSource)
“执行存储过程并返回输出参数的映射,按参数声明中的名称作为键..”
上一行的警告:List<Student> students = (List<Student>) result.get("out_refcursor"); 是:
类型安全:从对象到列表的未经检查的强制转换
我知道这只是一个编译时警告,当然我可以通过@SuppressWarnings("unchecked") 来抑制它。
问题:但是我该如何正确地投射它呢?
-
我尝试过的一种方法是
List<Student> students = castObject( result.get("out_refcursor")); @SuppressWarnings("unchecked") private static <T extends List<?>> T castObject(Object obj){ return (T)obj; }
我仍然必须将@SuppressWarnings("unchecked") 放入castObject() 方法中。而且我不知道这是否是正确的做法。
-
我尝试的第二种方法是,
List<?> students = castObject( result.get("out_refcursor")); Student student = (Student)students.get(0); private static <T extends List<?>> List<?> castObject(Object obj){ if(obj instanceof List<?>) { return (List<Student>)obj; } return null; }
欢迎任何建议/建议。
【问题讨论】:
-
如果你知道返回的值是
List<Student>,那就没问题了。 -
第一种方法很好,如果你知道它总是返回 List
如果你不确定它会返回什么,你应该使用你的第三种方法...... -
我知道它总是会返回
List<Student>,所以在这种情况下放置@SupressWarnings("unchecked") 是干净的编码吗?第三种方法也可以避免警告,但我觉得代码太多