SqlOutParameter out = new SqlOutParameter("out_refcursor",OracleTypes.CURSOR,new StudentRowMapper());
Run Code Online (Sandbox Code Playgroud)
//一些代码..
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
Run Code Online (Sandbox Code Playgroud)
execute()方法的定义:
Map<String, Object> org.springframework.jdbc.core.simple.SimpleJdbcCall.execute(SqlParameterSource parameterSource)
Run Code Online (Sandbox Code Playgroud)
"执行存储过程并返回输出参数的映射,按参数声明中的名称键入.."
以上警告: 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;
}
Run Code Online (Sandbox Code Playgroud)我仍然需要放入@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;
}
Run Code Online (Sandbox Code Playgroud)欢迎任何建议/意见.
只要你知道元素的类名,那样的东西就可以工作了List.这里有一个问题,硬编码ArrayList实例化.
public static <T> List<T> castList(Object obj, Class<T> clazz)
{
List<T> result = new ArrayList<T>();
if(obj instanceof List<?>)
{
for (Object o : (List<?>) obj)
{
result.add(clazz.cast(o));
}
return result;
}
return null;
}
Run Code Online (Sandbox Code Playgroud)
用法:
List<Student> students = castList(result.get("out_refcursor"), Student.class);
Run Code Online (Sandbox Code Playgroud)