使用Scala的宏斯卡拉反射 [英] Using Scala reflection in Scala macros

查看:110
本文介绍了使用Scala的宏斯卡拉反射的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Scala宏来生成一些代码,更具体地说,我希望该宏生成用于实例化抽象类的函数.例如,如果这是抽象类:

I'm trying to use Scala macros in order to generate some code, more specifically I would like the macro to generate a function that instantiates an abstract class. For example, if this is the abstract class:

abstract class Person {
  val name: String
  val age: Int
}

因此宏将如下所示:

  def m = macro _m
  def _m(c: Context): c.Expr[Any] = {
    import c.universe._
    c.Expr(c.parse("""
        (_name:String, _age:Int) => new Person{
            val name = _name
            val age = _age
        }   
    """))
  }

到目前为止,问题是宏当然需要更通用,并且必须基于给定类的反射信息来生成函数.

So far so good, the problem is that macro needs to be more general of course and to generate the function based on the reflection information of a given class.

我浏览了Scala反射和宏文档,但找不到如何创建可以访问给定类的反射信息的宏.

I went through the Scala reflection and macros documentation and I couldn't find how to create a macro that can access the reflection information of a given class.

我希望该宏看起来像这样

I would like that macro to look something like this

  def m = macro _m
  def _m(c: Context)(<Type of the class>): c.Expr[Any] = {
    import c.universe._
    c.Expr(c.parse("""
    <generate the function based on the type of the class>
    """))
  }

以及使用宏的外观如下:

and the use of the macro to look something like this:

val factoryFunction = m(typeOf[Person])

推荐答案

也许你的意思是这样的:

Maybe you mean something like this:

def m[T] = macro _m[T]
def _m[T: c.WeakTypeTag](c: Context) = {
  import c.universe._
  val typeOfT = weakTypeOf[T]
  // now that you have Type representing T, you can access all information about it, e.g.
  // members, type hierarchy, etc.
  ...
}

使用此方法,您需要确保始终以具体类型调用宏,例如这将不起作用:

Using this method you need to ensure that your macro is always called with concrete type, e.g. this will not work:

class Example[T] {
  val creatorOfT = m[T]
}

这篇关于使用Scala的宏斯卡拉反射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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