18

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 :(

JasonG
  • 5,794
  • 4
  • 39
  • 67

1 Answers1

34

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]]
}
Klaus
  • 885
  • 7
  • 11
  • Thanks - I literally just got this as I saw your answer. Using the implicit worked beautifully. – JasonG May 31 '14 at 23:00
  • 3
    `classTag[T].runtimeClass` is a little bit shorter – kiritsuku Jun 01 '14 at 00:14
  • 1
    @sschaef But it returns `Class[_]` and not `Class[T]`, in case it matters. – Alexey Romanov Jun 01 '14 at 17:52
  • sschaef is right. `classTag[T].runtimeClass` is a shorthand for `implicitly[reflect.ClassTag[T]].runtimeClass` and thus needs an `asInstanceOf[Class[T]]` as I posted – Klaus Jun 01 '14 at 20:41
  • @Klaus, is it also possible to derive the name of the class (string) from ClassTag[T] by using this approach? Please see [this question](https://stackoverflow.com/questions/48576345/scala-retrieve-class-name-from-classtag) – y2k-shubham Feb 02 '18 at 07:50