【问题标题】:Returning object of type specified in method arguments instead of AnyRef返回方法参数中指定类型的对象,而不是 AnyRef
【发布时间】:2016-02-19 08:10:35
【问题描述】:

我有以下方法:

@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 类型的实例?每次我使用这种方法时,我都想避免投射asInstanceOf。我知道使用EntityCacheManager 类型的泛型定义会很好,但它也是一个spring-managed bean,所以我认为使用泛型会引起麻烦。

【问题讨论】:

    标签: spring scala generics reflection


    【解决方案1】:

    您可以通过使用 ClassTag 类型类来使用更惯用的 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")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-03-24
      • 1970-01-01
      • 2017-02-25
      • 2017-10-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多