scala-reflect

ClassTag.runtimeClass.isInstance does not work for AnyVal

穿精又带淫゛_ 提交于 2019-12-01 11:39:08
问题 Working with scala ClassTags I have seen that classTag.runtimeClass.isInstance doesn't work properly when you use it with AnyVal objects. Here is a snippet where you can test it. Any ideas to make this work for AnyVal objects? import scala.reflect.ClassTag import scala.reflect.runtime.{universe => ru} object Test { def extractField[U: ru.TypeTag](json: Map[String, Any], field: String)(implicit classTag: ClassTag[U]): Option[U] = { json.get(field) match { case Some(value) => if(classTag

In Scala Reflection, How to get generic type parameter of a concrete subclass?

有些话、适合烂在心里 提交于 2019-11-29 10:05:42
Assuming that I have a Generic superclass: class GenericExample[T]( a: String, b: T ) { def fn(i: T): T = b } and a concrete subclass: case class Example( a: String, b: Int ) extends GenericExample[Int](a, b) I want to get the type parameter of function "fn" by scala reflection, so I select and filter through its members: import ScalaReflection.universe._ val baseType = typeTag[Example] val member = baseType .tpe .member(methodName: TermName) .asTerm .alternatives .map(_.asMethod) .head val paramss = member.paramss val actualTypess: List[List[Type]] = paramss.map { params => params.map { param

Getting subclasses of a sealed trait

心已入冬 提交于 2019-11-27 14:09:24
Is it possible (via macros, some form of Shapeless automagic or otherwise) to obtain a list of the subclasses of a sealed trait: At compile time? At runtime? You don't need any 3rd party library to do this: sealed trait MyTrait case object SubClass1 extends MyTrait case object SubClass2 extends MyTrait import scala.reflect.runtime.{universe => ru} val tpe = ru.typeOf[MyTrait] val clazz = tpe.typeSymbol.asClass // if you want to ensure the type is a sealed trait, // then you can use clazz.isSealed and clazz.isTrait clazz.knownDirectSubclasses.foreach(println) Output: object SubClass1 object

Getting subclasses of a sealed trait

时光总嘲笑我的痴心妄想 提交于 2019-11-26 16:05:33
问题 Is it possible (via macros, some form of Shapeless automagic or otherwise) to obtain a list of the subclasses of a sealed trait: At compile time? At runtime? 回答1: You don't need any 3rd party library to do this: sealed trait MyTrait case object SubClass1 extends MyTrait case object SubClass2 extends MyTrait import scala.reflect.runtime.{universe => ru} val tpe = ru.typeOf[MyTrait] val clazz = tpe.typeSymbol.asClass // if you want to ensure the type is a sealed trait, // then you can use clazz