alvinalexander.com | career | drupal | java | mac | mysql | perl | scala | uml | unix  

Scala example source code file (JavaReflectionRuntimes.scala)

This example Scala source code file (JavaReflectionRuntimes.scala) is included in my "Source Code Warehouse" project. The intent of this project is to help you more easily find Scala source code examples by using tags.

All credit for the original source code belongs to scala-lang.org; I'm just trying to make examples easier to find. (For my Scala work, see my Scala examples and tutorials.)

Scala tags/keywords

array, class, classloader, javareflectionresolvers, javareflectionruntimes, macro, macroruntime, macroruntimeresolver, nosuchmethodexception, reflection, runtime

The JavaReflectionRuntimes.scala Scala example source code

package scala.reflect.macros
package runtime

import scala.reflect.runtime.ReflectionUtils
import scala.reflect.macros.blackbox.{Context => BlackboxContext}
import scala.reflect.macros.whitebox.{Context => WhiteboxContext}
import java.lang.reflect.{Constructor => jConstructor}

trait JavaReflectionRuntimes {
  self: scala.tools.nsc.typechecker.Analyzer =>

  trait JavaReflectionResolvers {
    self: MacroRuntimeResolver =>

    def resolveJavaReflectionRuntime(classLoader: ClassLoader): MacroRuntime = {
      val implClass = Class.forName(className, true, classLoader)
      val implMeths = implClass.getMethods.find(_.getName == methName)
      // relies on the fact that macro impls cannot be overloaded
      // so every methName can resolve to at maximum one method
      val implMeth = implMeths getOrElse { throw new NoSuchMethodException(s"$className.$methName") }
      macroLogVerbose(s"successfully loaded macro impl as ($implClass, $implMeth)")
      args => {
        val implObj =
          if (isBundle) {
            def isMacroContext(clazz: Class[_]) = clazz == classOf[BlackboxContext] || clazz == classOf[WhiteboxContext]
            def isBundleCtor(ctor: jConstructor[_]) = ctor.getParameterTypes match {
              case Array(param) if isMacroContext(param) => true
              case _ => false
            }
            val Array(bundleCtor) = implClass.getConstructors.filter(isBundleCtor)
            bundleCtor.newInstance(args.c)
          } else ReflectionUtils.staticSingletonInstance(implClass)
        val implArgs = if (isBundle) args.others else args.c +: args.others
        implMeth.invoke(implObj, implArgs.asInstanceOf[Seq[AnyRef]]: _*)
      }
    }
  }
}

Other Scala source code examples

Here is a short list of links related to this Scala JavaReflectionRuntimes.scala source code file:

... this post is sponsored by my books ...

#1 New Release!

FP Best Seller

 

new blog posts

 

Copyright 1998-2021 Alvin Alexander, alvinalexander.com
All Rights Reserved.

A percentage of advertising revenue from
pages under the /java/jwarehouse URI on this website is
paid back to open source projects.