Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting object instance by string name in scala

I need the object (or "singleton object" or "companion object"... anything but the class) defined by a string name. In other words, if I have:

package myPackage object myObject 

...then is there anything like this:

GetSingletonObjectByName("myPackage.myObject") match {   case instance: myPackage.myObject => "instance is what I wanted" } 
like image 901
Dave Avatar asked Dec 16 '09 08:12

Dave


People also ask

Can I have a class and object with same name in a Scala file?

An object with the same name as a class is called a companion object. Conversely, the class is the object's companion class. A companion class or object can access the private members of its companion. Use a companion object for methods and values which are not specific to instances of the companion class.

Are Scala objects singletons?

Instead of static keyword Scala has singleton object. A Singleton object is an object which defines a single object of a class. A singleton object provides an entry point to your program execution.

What are companion objects in Scala?

A companion object in Scala is an object that's declared in the same file as a class , and has the same name as the class. For instance, when the following code is saved in a file named Pizza.scala, the Pizza object is considered to be a companion object to the Pizza class: class Pizza { } object Pizza { }


1 Answers

In scala 2.10 we can do like this

import scala.reflect.runtime.universe  val runtimeMirror = universe.runtimeMirror(getClass.getClassLoader)  val module = runtimeMirror.staticModule("package.ObjectName")  val obj = runtimeMirror.reflectModule(module)  println(obj.instance) 
like image 108
Nguyen Duc Dung Avatar answered Sep 23 '22 23:09

Nguyen Duc Dung