简体   繁体   English

与宏中的子类匹配

[英]Matching against subclasses in macro

I need to convert a string value into an actual type, so i decided to try a macro-way to do this. 我需要将字符串值转换为实际类型,所以我决定尝试宏方式来执行此操作。 I have a bunch of data types: 我有一堆数据类型:

sealed abstract class Tag(val name: String)
case object Case1 extends Tag("case1")
case object Case2 extends Tag("case2")
case object Case3 extends Tag("case3")
etc...

I want to write a simple resolver: 我想写一个简单的解析器:

val tag: Tag = TagResolver.fromString("case2")

This line should return Case2 respectively. 该行应分别返回Case2 I manager to do the following: 我经理要做以下事情:

def typeFromString(c: Context)(name: c.Expr[String]): c.Expr[Tag] = {
    import c.universe._
    val tag = typeTag[Tag]
    val accSymb = tag.tpe.typeSymbol.asClass
    val subclasses = accSymb.knownDirectSubclasses // all my cases

    subclasses.map { sub =>
      val name = sub.typeSignature.member(newTermName("name")).asMethod // name field
      ???
    }
  }

But how can i match name: c.Expr[String] against value of name field and if matched return the appropriate tag? 但是如何匹配name: c.Expr[String]name字段的值匹配,如果匹配则返回相应的标签?

I don't think there's reliable way of doing this, because knownDirectSubclasses can refer to classes that haven't been compiled yet, so we can't evaluate them. 我认为没有可靠的方法,因为knownDirectSubclasses可以引用尚未编译的类,因此我们无法评估它们。

If you can put these values as annotations on the classes, then these annotations can be read even when classes are being compiled in the current compilation run (via the Symbol.annotations API). 如果您可以将这些值作为注释放在类上,那么即使在当前编译运行中编译类(通过Symbol.annotations API),也可以读取这些注释。 Please note, however, that knownDirectSubclasses has known issues: https://issues.scala-lang.org/browse/SI-7046 . 但请注意,knownDirectSubclasses存在已知问题: https ://issues.scala-lang.org/browse/SI-7046。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM