Nick H
Nick H

Reputation: 11535

Accessing Scala nested objects through reflection

I've got some nested objects like this:

object Routes {
  object admin {
    def home = "/admin/home/"
    def module(m:Module) = "/admin/module/"+m.code
  }
}

Accessible via Routes.admin.module(mymod) and so on.

Given the Routes object, I want to be able to access the admin object by its name "admin", in order to expose it to the templating engine I'm using (Freemarker). This is the solution based on the standard Java Reflection API I've come up with that seems to work:

val obj = Routes
val key = "admin"
Class.forName(obj.getClass.getName+key+"$").getField("MODULE$").get(null)

This finds for the static field Routes$admin$.MODULE$ which is where the singleton object lives. Is there a neater way that doesn't require embedding knowledge of the naming conventions for Scala bytecode?

Upvotes: 3

Views: 1771

Answers (1)

Submonoid
Submonoid

Reputation: 2829

With the new Reflection API in Scala 2.10M4 this can be done with:

import scala.reflect.runtime.{universe => u}
val t = u.typeOf[Routes.type]
val adminName = u.newTermName("admin")
val admin = t.member(adminName)
// work with admin

Upvotes: 3

Related Questions