1

语境:

我正在开发一个在 Scala 中使用 JMX 的库。目标之一是为托管 Bean 提供强类型接口。我想类似于 Spring 框架 JMX 库。

目标:将 TabularData 反序列化为案例类的宏:

// interface for which I'd like to generate an implementation using a macro
trait JMXTabularAssembler[T <: Product] {
  def assemble(data: TabularData): T
}

object JMXAnnotations {
  case class Attribute(name: String) extends StaticAnnotation
}
case class example(
  @Attribute("name") name: String,
  @Attribute("age") age: Int,
  unmarked: String
)

问题:有很多使用q""插值器组成树的例子。但我不知道如何使用tq""插值器从类型上下文中提取案例类中的字段。

private def mkAssembler[T <: Product : c.WeakTypeTag](c: Context): c.universe.Tree = {
  import c.universe._
  val tt = weakTypeOf[T]
}

问题:如何使用 QuasiQuote 机制来解构我的案例类的字段,以便我可以遍历它们并使用我的注释过滤掉字段(我的Attribute注释在我目前采用的方法中不可用)。以下以声明顺序返回带有注释的字段是我所追求的。

private def harvestFieldsWithAnnotations[T<: Product: c.WeakTypeTag](c: Context): 
    List[(c.universe.Name, String, c.universe.Type,   List[c.universe.Annotation])] = ???

奖励:目标是获取属性字段,为每个字段生成树,从中提取字段TabularData并使用这些树创建JMXTabularAssemblerFunctor。如果您可以向我展示如何为上面的示例执行此操作,它将引导我的努力:D。


我尝试过的:我开始使用反射来解决问题。这似乎不是正确的方法。片段:

...
val dec = tt.decls.sorted
def getFields = dec.withFilter( t=> t.isTerm && ! t.isMethod)
def getCaseAccessors = dec.withFilter( t => t.isMethod && t.asMethod.isCaseAccessor)

dec.foreach { d=>
  println(d.name, d.annotations)
}

getFields.foreach { f =>
  println(f.annotations)
}

val types = getCaseAccessors.map { d =>
  println(d.annotations)
  (d.name, tt.member(d.name).asMethod.returnType)
}
...
4

1 回答 1

0

以下方法可以解决问题,它不使用准引号。关键是访问代表案例类(accessed调用)的字段访问器的符号的支持字段。

private def harvestFieldsWithAnnotations[T <: Product : c.WeakTypeTag](c: Context) = {
    import c.universe._
    val tt = weakTypeOf[T]

    tt.decls.sorted.filter(t => t.isMethod && t.asMethod.isCaseAccessor).map { ca =>
      val asMethod = tt.member(ca.name).asMethod
      (ca.name, asMethod.returnType, asMethod.accessed.annotations)
    }
  }

字段注释不会被保留,除非它们明确地用scala.annotation.meta.field.

所以Attribute注释应该是:

@field
case class Attribute(name: String) extends StaticAnnotation
于 2015-07-22T15:26:18.147 回答