如何使用 Scala ToolBox 反映在运行时定义的类的方法的具体返回类型? [英] How to reflect concrete return types for methods of classes defined at runtime using the Scala ToolBox?

查看:50
本文介绍了如何使用 Scala ToolBox 反映在运行时定义的类的方法的具体返回类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当反射类 Clsfoo() 方法时,我们可以使用以下内容轻松获取具体的返回类型.

When reflecting the foo() method of the class Cls we can easily get the concrete return type using the following.

class Cls {
  def foo() =
    List("A", "B")
}

val classType = ru.typeOf[Cls]
val classMirror = toolbox.mirror.reflectClass(classType.typeSymbol.asClass)
val ctorSymbol = classType.decl(ru.termNames.CONSTRUCTOR).asMethod
val methodSymb = classType.decl(ru.TermName("foo")).asMethod
val ctor = classMirror.reflectConstructor(ctorSymbol)
val instance = ctor()
val im = toolbox.mirror.reflect(instance)
val foo = im.reflectMethod(methodSymb)
println(foo())  // List(A, B)
println(methodSymb.returnType) // List[String]

但是,如果我们在运行时通过工具箱定义类Cls,然后使用相同的方法反射过程,我们只会得到抽象返回类型(List)foo() 方法.

However, if we define the class Cls at runtime via the toolbox and then use the same method reflection process, we will only get the abstract return type (List) of the foo() method.

import ru._

val tree =
  q"""class Cls {
        def foo() =
          List("A", "B")
    }""".asInstanceOf[ru.ClassDef]

val classSymbol = toolbox.define(tree).asClass
val classType = classSymbol.selfType

val classMirror = toolbox.mirror.reflectClass(classType.typeSymbol.asClass)
val ctorSymbol = classType.decl(ru.termNames.CONSTRUCTOR).asMethod
val methodSymb = classType.decl(ru.TermName("foo")).asMethod
val ctor = classMirror.reflectConstructor(ctorSymbol)
val instance = ctor()
val im = toolbox.mirror.reflect(instance)
val foo = im.reflectMethod(methodSymb)
println(foo())  // List("A", "B")
println(methodSymb.returnType)  // List

为什么这些代码片段会产生不同的结果?

Why do these code snippets produce different results?

如果Cls是在运行时使用工具箱定义的,我们如何反映foo()方法的具体返回类型?

How can we reflect the concrete return type of the foo() method if Cls is defined at runtime using the toolbox?

推荐答案

我想问题在于类型擦除.

I guess the thing is in type erasure.

尝试更换

val classType = classSymbol.selfType

val classType = toolbox.eval(q"scala.reflect.runtime.universe.typeOf[$classSymbol]").asInstanceOf[ru.Type]

那么methodSymb.returnType就是List[String].

这篇关于如何使用 Scala ToolBox 反映在运行时定义的类的方法的具体返回类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆