Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.6k views
in Technique[技术] by (71.8m points)

scala - How to get ClassTag form TypeTag, or both at same time?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...