2

I would like to be able to perform the following code:

abstract class A[T <: AnyRef]{
  def whichClass: Class[_] = classOf[T]
}

case class X()

object B extends A[X]

object Main{
  def main(args: Array[String]){
    B.whichClass //should return classOf[X]
  }
}

Clearly, it doesn't work in this form, since classOf[T] can be only assignged to class, not type. A got an error:

error: class type required but T found
def whichClass: Class[_] = classOf[T]

Any idea how solve this problem in another way?

1 Answer 1

9

Use ClassManifest.

abstract class A[T <: AnyRef : ClassManifest] {
  def whichClass = classManifest[T].erasure
}

case class X()

object B extends A[X]

object Main{
  def main(args: Array[String]): Unit = {
    println(B.whichClass) // prints 'class X'
  }
}
Sign up to request clarification or add additional context in comments.

1 Comment

@missing, any idea if this approach will change with new reflection in 2.10?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.