2014-06-19 77 views
4

我创建了以下代码片段,用作scala类型为java类型的编码生成器。scala宏创建java bean类时发生未知类型错误

object Macros { 
    def encode[A <: Product, B](value:A):B = macro MacrosImpl.encode_impl[A, B] 
} 

class MacrosImpl(val c:Context) { 
    import c.universe._ 
    def encode_impl[ScalaType: c.WeakTypeTag, JavaType: c.WeakTypeTag](value:c.Expr[ScalaType]) = { 

    val scalaType: WeakTypeTag[ScalaType] = implicitly[WeakTypeTag[ScalaType]] 

    val fields = scalaType.tpe.typeSymbol.companion.typeSignature.members.collectFirst { 
     case method if method.name.toString == "apply" => method 
    }.toList.flatMap(_.asMethod.paramLists.flatten). 
     map{ 
     case s if s.name.toString == "id" => q"underlying.setId($value.$s.orNull)" 
     case s => q"underlying.${c.universe.newTermName("set" + s.name.toString.capitalize) }($value.$s)" 
    } 

    val javaType: WeakTypeTag[JavaType] = implicitly[WeakTypeTag[JavaType]] 

    q""" 
     val underlying = new ${javaType.tpe}() 
     ..$fields 
     underlying 
     """ 
    } 
} 

这个编译在宏项目编译时就好了,当我尝试使用它。它在使用库项目编译时引发异常。

private val x: IpDataEntry = IpDataEntry(None, "a", "a") 
println(Macros.encode[IpDataEntry, Underlying](x)) //not comp 


[error] Unknown type: <error>, <error> [class scala.reflect.internal.Types$ErrorType$, class scala.reflect.internal.Types$ErrorType$] TypeRef? false 
[trace] Stack trace suppressed: run 'last web/compile:compile' for the full output. 
[error] (web/compile:compile) scala.reflect.internal.FatalError: Unknown type: <error>, <error> [class scala.reflect.internal.Types$ErrorType$, class scala.reflect.internal.Types$ErrorType$] TypeRef? false 
[error] Total time: 12 s, completed Jun 19, 2014 11:53:42 AM 

我被困在这里,我在代码中找不到任何错误。

Scala版本是2.11.1。

+0

您能否将整个项目发布在公共场合,例如:在github? –

+0

U拯救了我的生命,非常感谢:) – jdevelop

回答

1

我自己找到了解决方案。 in code block

q"underlying.setId($value.$s.orNull)" 

$s不是TermName。所以我将其修改为

q"underlying.setId($value.${c.universe.newTermName(s.name.toString)}.orNull)" 

无论如何,如果该错误指向语法树中的正确问题,那么它非常有用。我浪费了大约2天的时间来发现问题。