Search code examples
scalascala-macrosscala-macro-paradise

Use a static Java declaration in macro implementation


I am trying to use a static method on a Java class, T, in a macro implementation:

def macroImpl[T : c.WeakTypeTag](c: Context): c.Expr[ResultType] = {
  import c.universe._
  val tpe = weakTypeOf[T]
  val someStaticMethod = tpe.declaration(c.universe.newTermName("someStaticMethod")).asMethod
  c.Expr[ResultType] { q""" new ResultType {
    def myMethod = ${someStaticMethod.name.toTermName}  
  }"""}
}

This does not work. When I print out all the members and declarations of tpe, the static methods that I want to use are not there. How do I access these static methods and use them in the quasiquote?

I am using version 2.1.0 of the macro-paradise compiler plugin for scala 2.10.6.


Solution

  • After seeing @som-snytt's comment, I investigated how to access the companion object. The code ended up looking something like this:

    def macroImpl[T : c.WeakTypeTag](c: Context): c.Expr[ResultType] = {
      import c.universe._
      val tpe = weakTypeOf[T]
      val companion = tpe.typeSymbol.companionSymbol
      c.Expr[ResultType] { q""" new ResultType {
        def myMethod = ${companion.name.toTermName}.someStaticMethod  
      }"""}
    }
    

    I look up the companion symbol and then call the method someStaticMethod on it in the quasiquote. This seems to do what I want.

    I can get the declarations of companion by doing companion.typeSignature.declarations