Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/spring/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Spring 返回在方法参数(而不是AnyRef)中指定的类型的对象_Spring_Scala_Generics_Reflection - Fatal编程技术网

Spring 返回在方法参数(而不是AnyRef)中指定的类型的对象

Spring 返回在方法参数(而不是AnyRef)中指定的类型的对象,spring,scala,generics,reflection,Spring,Scala,Generics,Reflection,我有以下方法: @org.springframework.stereotype.Service class EntityCacheManager { def get(cacheId: String, entityClass: Class[_]): AnyRef = { ... } //... } 所以要使用它,我必须写下: val cachedEntity = entityCacheManager.get(cacheId, classOf[SomeEntity]).asInstance

我有以下方法:

@org.springframework.stereotype.Service
class EntityCacheManager {
  def get(cacheId: String, entityClass: Class[_]): AnyRef = { ... }
  //...
}
所以要使用它,我必须写下:

val cachedEntity = entityCacheManager.get(cacheId, classOf[SomeEntity]).asInstanceOf[SomeEntity]

是否有某种方法可以使
EntityCacheManager.get()
返回方法参数中指定的
entityClass
类型的实例?每次使用此方法时,我都希望避免将
转换为
的实例。我知道使用类型
EntityCacheManager
的泛型定义会很好,但它也是一个spring管理的bean,所以我认为使用泛型会带来麻烦。

您可以通过使用ClassTag typeclass来使用更为惯用的scala方法

class EntityCacheManager {
  def get[T: ClassTag](cacheId: String): T = {
    val entityClass = implicitly[ClassTag[T]].runtimeClass
    val myObject: T = ??? // you retrieve your object somehow using entityClass
    myObject
  }
}
您现在可以这样使用它:

val myEntityClassInstance = get[MyEntityClass]("key")