Skip to content

use scala reflection #13

@squito

Description

@squito

switch to scala reflection, which will allow sumac to support types like List[Int]. Finally found the key thing required for this:

import scala.reflect.runtime.{universe => ru}
def getType[T: ru.TypeTag](obj: T) = ru.typeTag[T].tpe
class Foo
class Bar extends Foo
val b: Foo = new Bar
scala> getType(b)
res0: reflect.runtime.universe.Type = Foo

scala> b.getClass()
res1: Class[_ <: Foo] = class Bar


class Foo {
  def doStuff() = { 
    this.getClass().getDeclaredField("y")
  }
}

class Bar extends Foo {
  val x: Int = 17
  val y: List[Int] = List(1,2,3)
}


def getRuntimeType[A](item: A) = {
  val mirror = ru.runtimeMirror(this.getClass.getClassLoader)
  mirror.classSymbol(item.getClass).toType
}


val b : Foo = new Bar
scala> getRuntimeType(b).members.collect{case x if x.isTerm => x.asTerm}.filter{_.isGetter}.map{x => x -> x.typeSignature}.toMap
Map(value y -> => scala.List[scala.Int], value x -> => scala.Int)

http://stackoverflow.com/questions/17010237/using-scala-reflection-to-find-most-derived-runtime-type

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions