How to get ClassTag form TypeTag, or both at same

2019-01-12 05:26发布

I have some code like this:

class ReflectiveJsonFormat[T:TypeTag] extends JsonFormat[T] {
  def write(x: T) : JsValue = {
   val t = typeOf[T]
   val getters = t.declarations.filter { s => s.isMethod && s.asMethod.isGetter }
   val mirror = runtimeMirror(this.getClass.getClassLoader)
   val instanceMiror = mirror.reflect(x)
  }
}

That last line fails with:

No ClassTag available for T

I thought TypeTag was more info than a ClassTag? Can I get the ClassTag from the TypeTag? If not, is there some syntax for saying that T has two context bounds -- both TypeTag and ClassTag? Or, how would you otherwise fix this code?

2条回答
男人必须洒脱
2楼-- · 2019-01-12 05:54

Well scala does support multiple context bounds if that is what you are after:

class ReflectiveJsonFormat[T:TypeTag:ClassTag] 
查看更多
放我归山
3楼-- · 2019-01-12 05:59

The library doesn't provide a built-in method that directly converts a TypeTag to a ClassTag, but you can write one:

import reflect.runtime.universe._
import reflect.ClassTag

def typeToClassTag[T: TypeTag]: ClassTag[T] = {
  ClassTag[T]( typeTag[T].mirror.runtimeClass( typeTag[T].tpe ) )
}

Then in your method just add before the implicit ClassTag is needed:

implicit val c = typeToClassTag[T]
查看更多
登录 后发表回答