1

Is it possible in Scala to get the singleton instance of an object when I only have the class? Consider

object A {}

def getSingletonInstance[T](x: Class[T]): Option[T] = {
  // output the singleton, if x is a singleton class i.e. defined by an object
  // is this possible?
}

getSingletonInstance(A.getClass) // --> should return Some[A]
Fabian Schmitthenner
  • 1,696
  • 10
  • 22

1 Answers1

3

There are many questions on SO discussing different ways of doing this. One of them I referenced in a comment to your question. Here is another one, using "official" scala reflection: Get companion object instance with new Scala reflection API

If you don't mind an approach, involving a little "hacking" (as in using some unofficial/undocumented/coincident features rather than an official API), you can do it much easier with something like this:

val clazz = Class.forName(x.getName + "$")
val singleton = clazz.getField("MODULE$").get(clazz)

Note that a companion object of class T does not have to be an instance of T, so the declaration of your getSingletonInstance won't always work.

EDIT I did not realize that you were passing the class of the object itself to your function, not the companion class. In that case, you don't need to append it with dollar sign in the above code, and don't even need the first line at all. You can just do x.getField("MODULE$").get(x)

Community
  • 1
  • 1
Dima
  • 39,570
  • 6
  • 44
  • 70