将类型标识符传递给静态宏注释

问题描述

是否可以将类型标识符传递给宏注释?这是我的意思:

@compileTimeOnly("Compile-time only annotation")
class mymacro(val typeName: universe.TypeName) extends StaticAnnotation { // <-- does not work
  def macroTransform(annottees: Any*): Any = macro impl
}

object mymacro {
  def impl(c: whiteBox.Context)(annottees: c.Expr[Any]*) = //...
}

用例:

trait SomeTrait

@mymacro(SomeTrait)
class Test {
    //...
}

或者也许还有其他方法可以将任意非通用类型的类型标识符传递给宏注释实现?

背后的动机:我需要生成一些class Test成员函数def foo,具体取决于作为参数传递给宏注释(SomeTrait)的类型。

解决方法

例如,您可以将openCamera作为字符串传递

typeName

用法:

import scala.annotation.{StaticAnnotation,compileTimeOnly}
import scala.language.experimental.macros
import scala.reflect.macros.blackbox

@compileTimeOnly("Compile-time only annotation")
class mymacro(typeName: String) extends StaticAnnotation {
  def macroTransform(annottees: Any*): Any = macro mymacro.impl
}

object mymacro {
  def impl(c: blackbox.Context)(annottees: c.Tree*): c.Tree = {
    import c.universe._
    val typeName = TypeName(c.prefix.tree match {
      case q"new mymacro(${str: String})" => str
    })

    println(typeName)

    q"..$annottees"
  }
}

Getting Parameters from Scala Macro Annotation

如果您更喜欢 @user 在评论中提出的伴随对象方法,则可以

trait SomeTrait

@mymacro("SomeTrait")
class Test 

// scalac: SomeTrait

用法:

import scala.annotation.{StaticAnnotation,compileTimeOnly}
import scala.language.experimental.macros
import scala.reflect.macros.blackbox

@compileTimeOnly("Compile-time only annotation")
class mymacro(companionObject: Any) extends StaticAnnotation {
  def macroTransform(annottees: Any*): Any = macro mymacro.impl
}

object mymacro {
  def impl(c: blackbox.Context)(annottees: c.Tree*): c.Tree = {
    import c.universe._

    val companionTrait = c.typecheck(c.prefix.tree) match {
      case q"new mymacro($arg)" => arg.symbol.companion
    }

    println(companionTrait)

    q"..$annottees"
  }
}

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...