项目源代码中出现例如以下代码:
HibernateTemplate ht =……
List<Object[]> tempList = ht.find(String querystring);
查看api发现HibernateTemplate的find(String querystring)方法返回的是一个List<Object>对象,当时就比較纳闷了。难道Object对象能强转为Object数组?当然不能。那是为什么呢?find方法返回的list本质上就是List<Object[]>类型的。
追踪Spring api和hibernate api能够略知一二。
public List <span style="color:#cc0000;">find(String queryString)</span> throws DataAccessException {
return <span style="color:#cc0000;">find(queryString, (Object[]) null)</span>;
}
public List <span style="color:#cc0000;">find(final String queryString, final Object[] values) </span>throws DataAccessException {
return (List) execute(new HibernateCallback() {
public Object doInHibernate(Session session) throws HibernateException {
Query queryObject = session.createQuery(queryString);
prepareQuery(queryObject);
if (values != null) {
for (int i = 0; i < values.length; i++) {
queryObject.setParameter(i, values[i]);
}
}
return <span style="color:#cc0000;">queryObject.list()</span>;
}
}, true);
}
public List list()
throws HibernateException
Return the query results as a List. If the query contains multiple results pre row, the results are returned in an instance of Object[].
Returns:
the result list
Throws:
HibernateException
解决问题的同一时候,也发现了另外一个问题:Object[] 能够转型为Object,这是为什么呢?查证得知。java中数组也是对象,Object是根对象。
Object[] obj1= new Object[2];
Object obj2 =obj1;