JasonG
JasonG

Reputation: 5962

How do I get the classOf a ClassTag?

This doesn't work - is there any way I can keep my code generified and somehow reflect the classOf a ClassTag??

class Foo[T : reflect.ClassTag] { def foo = classOf[T] }

<console>:7: error: class type required but T found
   class Foo[T : reflect.ClassTag] { def foo = classOf[T] }

It seems this should work but alas :(

Upvotes: 18

Views: 9077

Answers (1)

Klaus
Klaus

Reputation: 895

Yes, that's possible.

class Foo[T: reflect.ClassTag] {
  def ctag = implicitly[reflect.ClassTag[T]]
  def foo: Class[T] = ctag.runtimeClass.asInstanceOf[Class[T]]
}

or shorter:

class Foo[T](implicit ctag: reflect.ClassTag[T]) {
  def foo: Class[T] = ctag.runtimeClass.asInstanceOf[Class[T]]
}

Upvotes: 34

Related Questions