如何在Scala中获取泛型类型的运行时类?

问题描述 投票:3回答:1
import scala.reflect.runtime.universe._
import scala.reflect.ClassTag
import scala.reflect.classTag

def getTypeTag[T: TypeTag](obj: T) = println(typeTag[T].tpe)

class Entity
{
    def greet = println("Hello!")
}

class Point[T : TypeTag](val x : T, val y :T) extends Entity

val p = new Point[Int](2,5)
val p2 = new Point[Float](1.0f,-5.0f)
val p3 = new Point[Double](4.0,-7.0)

val path = Array[Entity](p,p2,p3)

path.foreach(getTypeTag(_))

这个小代码片段写入stdout

Helper.this.Entity
Helper.this.Entity
Helper.this.Entity

我想写它

Helper.this.Point[Int]
Helper.this.Point[Float]
Helper.this.Point[Double]

我知道有很多关于scala反射的问题,我读过很多但仍然没有理解TypeTag,Manifest和ClassTag之间的区别;我也无法得到这个非常基本的例子。任何帮助将不胜感激。

提前致谢

scala reflection
1个回答
1
投票

Short, reasonable answer:

你不能。不要那样做。你为什么一开始就需要这个?你可能做错了......

Unsatisfactory answer:

def printType(a: Any) =
  a match {
    case p: Point[_] =>
      val clazz = p.getClass.getName
      val tname = p.x.getClass.getName
      println(s"$clazz[$tname]")
    case _ =>
      println("yolo")
  }

class Entity 

class Point[T](val x: T, val y: T) extends Entity

val p = new Point[Int](2,5)
val p2 = new Point[Float](1.0f,-5.0f)
val p3 = new Point[Double](4.0,-7.0)

val path = Array[Entity](p, p2, p3)

path.foreach(printType)

Actual answer:

使用无形Typeable

import shapeless._

val path = p :: p2 :: p3 :: HNil

object printType extends Poly1 {
  implicit def case0[T](implicit t: Typeable[T]) =
    at[T](_ => t.describe)
}

path.map(printType).toList.foreach(println)
© www.soinside.com 2019 - 2024. All rights reserved.