scala - 使用 Shapeless 的类与类型注释
问题描述
根据 scala文档,有四种注释:
- 类注解:
@ClassAnnotation case class Foo(...)
- 变量/值注释:
@ValAnnotation val field: String
- 类型注释:
field: String @TypeAnnotation
- 表达式注释
通过使用shapeless.Annotation
and shapeless.Annotations
,很容易从案例类中获取类和变量注解(1&2)。如何获取其字段的类型注解(3)?
例子:
@ClassAnnotation
case class Foo(
@ValAnnotation field: String @TypeAnnotation
)
解决方案
你可以写一个宏
import scala.language.experimental.macros
import scala.reflect.macros.blackbox
def getAnnotation[A]: Any = macro impl[A]
def impl[A: c.WeakTypeTag](c: blackbox.Context): c.Tree = {
import c.universe._
println(weakTypeOf[A].typeSymbol.annotations) // List(ClassAnnotation)
println(weakTypeOf[A]
.member(termNames.CONSTRUCTOR)
.asMethod
.paramLists
.map(_.map(_.annotations))
) // List(List(List(ValAnnotation)))
println(weakTypeOf[A]
.member(termNames.CONSTRUCTOR)
.asMethod
.paramLists
.map(_.map(_.typeSignature match {
case AnnotatedType(annots, _) => annots
case _ => List()
})) // List(List(List(TypeAnnotation)))
)
q""
}
import scala.annotation.StaticAnnotation
case class ClassAnnotation() extends StaticAnnotation
case class ValAnnotation() extends StaticAnnotation
case class TypeAnnotation() extends StaticAnnotation
@ClassAnnotation
case class Foo(
@ValAnnotation field: String @TypeAnnotation
)
getAnnotation[Foo]
推荐阅读
- apache-spark - pyspark 从 spark 数据框列创建一个不同的列表并在 spark sql where 语句中使用
- c# - 程序世界生成器生成重叠的地砖 - Unity3D C#
- performance - 如何改进我的 LED 显示屏代码,使其实时反应
- javascript - 我如何使用 Livewire 和 CkEditor 4 传递数据?
- python - 使用列表中的数据更新 JSON 文件中的值
- c# - DataProtectorTokenProvider ValidateAsync 始终为 False
- c# - 当我尝试通过解决方案中的另一个项目访问数据时,为什么数据库无法在我的 .NET Web 应用程序项目中初始化?
- django - 带有条件 WHERE 的 Django3 ListView
- powershell - PowerShell Compare-Object 和 Export-Csv 导出错误数据
- ffmpeg - ffplay -noborder 选项缺少参数