我是 Scala 的新手,所以这很可能是一个非常明显的错误。但是,我试图将 List[Object] 转换为 List[A],其中 A 是类中的参数。
class AbstractHibernateDAO[A<:Serializable]{
def findAll: List[A] = {
val objList = currentSession.createQuery("from " + clazz.getName()).list()
objList.map{_.asInstanceOf[A]}
}
}
Eclipse 正在呕吐:
type mismatch; found : ?0(in method findAll) => A where type ?0(in method findAll) required: (some other)?0(in method findAll) => ? where type (some other)?0(in method findAll) AbstractHibernateDAO.scala /springHibernateNoXML/src/main/scala/my/package
我也尝试过长表格
objList.map{obj => obj.asInstanceOf[A]}
并得到相同的结果。
谁能帮我一把?
[编辑-附加信息]
对于那些要求的人,这是完整的清单:
package name.me
import java.io.Serializable
import java.util.List
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.beans.factory.config.BeanDefinition
import org.springframework.context.annotation.Scope
import org.springframework.orm.hibernate3.HibernateTemplate
import org.springframework.stereotype.Repository
import com.google.common.base.Preconditions
import org.hibernate.SessionFactory
import org.hibernate.Session
import collection.JavaConversions._
@Repository
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
class AbstractHibernateDAO[A<:Serializable]{
val clazz: Class[A] = null
@Autowired val sessionFactory: SessionFactory = null
def currentSession: Session = {
sessionFactory getCurrentSession
}
def findOne(id: Long): A = {
Preconditions checkArgument(id != null)
currentSession.get(clazz, id).asInstanceOf[A]
}
def findAll: List[A] = {
val objList = currentSession.createQuery("from " + clazz.getName()).list()
objList.map(_.asInstanceOf[A])
//This works
//objList.asInstanceOf[List[A]]
}
def save(entity:A){
Preconditions checkNotNull entity
currentSession persist entity
}
def update(entity: A){
Preconditions checkNotNull entity
currentSession merge entity
}
def delete(entity: A){
Preconditions checkNotNull entity
currentSession delete entity
}
def deleteById(entityId: Long){
Preconditions checkNotNull entityId
val entity = findOne(entityId)
Preconditions checkNotNull entity
delete(entity)
}
}