Reputation: 1980
I have the following method:
@org.springframework.stereotype.Service
class EntityCacheManager {
def get(cacheId: String, entityClass: Class[_]): AnyRef = { ... }
//...
}
So to use it, i have to write this:
val cachedEntity = entityCacheManager.get(cacheId, classOf[SomeEntity]).asInstanceOf[SomeEntity]
Is there some way to make EntityCacheManager.get()
returning instance of type entityClass
which is specified in method params? I'd like to avoid casting asInstanceOf
every time i use this method. I know it would be nice to use generic definition of type EntityCacheManager
, but it's also a spring-managed bean, so i think using generics will cause troubles.
Upvotes: 1
Views: 39
Reputation: 5546
You can use a more idiomatic scala approach by using the ClassTag typeclass
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
}
}
you can now use it like this:
val myEntityClassInstance = get[MyEntityClass]("key")
Upvotes: 1