There are several problems in your code. First, as you already said, the type will be erased, second object
s (object FooCompanionObject[f <: Foo]
) don't take type parameters and third, object
s can not be extended (object Bar extends FooCompanionObject
). To do what you want, you have to create an abstract base class for your companion objects, that takes a type parameter, which may be constrained to a specific type if you like, and has to be context bound on ClassTag
. From the ClassTag
you can then get the runtime class by calling runtimeClass
on it. The final solution could look like this:
import scala.reflect.ClassTag
import scala.reflect.classTag
trait Foo
abstract class Companion[A <: Foo : ClassTag] {
val fClazz = classTag[A].runtimeClass
}
class Bar extends Foo
object Bar extends Companion[Bar]
scala> Bar.fClazz
res2: Class[_] = class Bar