Created
January 7, 2015 16:33
-
-
Save darkjh/311761f9c4f0bdad35fb to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.lang.reflect.ParameterizedType | |
import com.google.common.reflect.TypeToken | |
import scala.reflect.ClassTag | |
import scala.reflect.runtime.universe._ | |
class KV[I, O] | |
case class A[T] { | |
val tok = new TypeToken[T](getClass) {} | |
} | |
class B[T: ClassTag] { | |
val v = implicitly[ClassTag[T]] | |
val clazz = implicitly[ClassTag[T]].runtimeClass | |
val tok = TypeToken.of(clazz).asInstanceOf[TypeToken[T]] | |
} | |
class C[T: TypeTag] { | |
val tpe = typeOf[T] | |
def typeArgs(tp: Type) = tp match { | |
case TypeRef(_, _, args) => args | |
case _ => Nil | |
} | |
} | |
object TypeTokenTest extends App { | |
val a = new A[KV[Integer, String]]{} | |
println(a.tok) | |
println(a.tok.getType.asInstanceOf[ParameterizedType].getActualTypeArguments.toList) | |
val b = new B[KV[Integer, String]]{} | |
println(b.tok) // not ok | |
val c = new C[KV[Integer, String]] | |
println(c.tpe.asInstanceOf[TypeRefApi].args) | |
println(c.typeArgs(c.tpe)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment