Scala - obtaining a class object from a generic type

dhg picture dhg · Nov 21, 2011 · Viewed 17.2k times · Source

Is it possible to create a Class object purely from a generic parameter? For example:

class myclass[T] { 
  def something(): Class[_ <: T] = 
    classOf[T] //this doesn't work
}

Since the type will have been erased at runtime, it seems like this a job for manifests, but I haven't found an example that demonstrates this particular usage. I tried the following, but it doesn't work either:

class myclass[T] { 
  def something()(implicit m: Manifest[T]): Class[_ <: T] = 
    m.erasure //this doesn't work
}

I suspect this failure is due to, as the API points out, there is no subtype relationship between the type of m.erasure's result and T.

EDIT: I'm not really interested in what the type T is, I just need an object of type Class[_ <: T] to pass to a method in the hadoop framework.

Any pointers?

Answer

Ali Salehi picture Ali Salehi · Oct 18, 2013
def myClassOf[T:ClassTag] = implicitly[ClassTag[T]].runtimeClass