Scala: Retrieve class-name from ClassTag

2020-04-16 05:27发布

问题:

I'm writing a generic method that can convert Any type argument to the an object of passed ClassTag[T] type, if possible.

def getTypedArg[T: ClassTag](any: Any): Option[T] = {
      any match {
        case t: T => Some(t)
        case invalid =>
          logger.warn(s"Invalid argument: $invalid")
          None
      }
}

I want the log message to be more precise like this:

case invalid => logger.warn(s"Invalid argument: $invalid of type $className")

How can I retrieve className from the ClassTag[T]?

Alternatively, is there a fundamentally different approach that can serve my use-case better?

回答1:

Add this import statement

import scala.reflect._

and change the logging statement as,

logger.warn(s"Invalid argument: $invalid of type ${classTag[T].runtimeClass}")

This is taken from Scala classOf for type parameter