I have some code to instantiate a random class like this:
trait T
class A extends T
class B extends T
class C extends T
def createRandomT = {
val choices = Vector(classOf[A], classOf[B], classOf[C])
val cls = new scala.util.Random().shuffle(choices).head
instantiateT(cls)
}
def instantiateT(cls: Class[_ <: T]) = {
ClassManifest.fromClass(cls) match {
case c if c <:< classManifest[A] => new A
case c if c <:< classManifest[B] => new B
case c if c <:< classManifest[C] => new C
}
}
This works, but after upgrading to 2.10 instantiateT
gives various deprecation warnings.
Any hints how to replicate the functionality with ClassTag
and/or TypeTag
?
Edit: As pointed out by Daniel this works:
cls match {
case c if c.isAssignableFrom(classOf[A]) => new A
case c if c.isAssignableFrom(classOf[B]) => new B
case c if c.isAssignableFrom(classOf[C]) => new C
}
如果您有一个Class
,则应该只使用isAssignableFrom
。
case c if cls.isAssignableFrom(c.getClass()) => new A
I am not sure why it has to be so complicated... Surely if you already have a Class
instance you can just call Class.newInstance
? Like so:
def instantiateT(cls: Class[_ <: T]) = cls.newInstance
Or maybe you are performing a match because in your real code each class has a separate list of (default) argument to pass to the constructor?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.