问题描述
我正在编写用于注释案例类的Scala宏注释@model
,它会基于注释案例类的字段自动将一些元数据添加到注释类的伴随对象中.
I'm writing a Scala macro annotation @model
used to annotate my case classes and which automatically adds some metadata to the companion object of the annotated class, based on the fields of the annotated case class.
我想获得有关case类参数类型的更多信息,特别是检查它们是否实现了某种特征.我以为为它们获取WeakTypeTag
是可行的方法,但是我似乎无法像从def宏中获取它们那样获得方法.
I would like to obtain more information about the type of the case class's parameters, especially, check if they implement a certain trait. I thought obtaining a WeakTypeTag
for them was the way to go, but I can't seem to get one the way they are obtained in def macros.
具体而言:在这种情况下,我想从@model
的宏实现中得知,User
类的address
字段具有扩展ModelObject
的类型,并且不.我可以这样做吗?
Concretely: I want to be able to tell in this case, from the macro implementation of @model
, that the address
field of the User
class has a type which extends ModelObject
, and that date
doesn't. Can I do that?
trait ModelObject
@model case case Address(street: String, city: String) extends ModelObject
@model case class User(name: String, since: Date, address: Address) extends ModelObject
推荐答案
用于宏注释参数的树是有意未键入的.但是,运行c.typeCheck(q"(??? : <tree that represents the parent>)").tpe
将提供缺少的信息.在类型检查之前,请不要忘记duplicate
该树,因为c.typeCheck
会在适当位置突变该树,这可能是不希望的.
Trees that go into macro annotation arguments are purposefully untyped. However running c.typeCheck(q"(??? : <tree that represents the parent>)").tpe
will provide the missing information. Don't forget to duplicate
that tree before typechecking, because c.typeCheck
mutates the tree in place, which might be undesireable.
c.typeCheck
的功能受到限制.有关某些示例,请参见在处理宏注释.
There are limitations to what c.typeCheck
can do. For some examples of that, see Can't access Parent's Members while dealing with Macro Annotations.
这篇关于在Scala宏批注中获取给定类型的WeakTypeTag的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!