Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala instantiate objects from String classname

I have a trait, Action, that many different classes, ${whatever}Action, extend. I'd like to make the class that is in charge of instantiating these Action objects dynamic in the sense that it will not know which of the extending objects it will be building until it is passed a String with the name. I want it to take the name of the class, then build the object based on that String.

I'm having trouble finding a concise/recent answer regarding this simple bit of reflection. I was hoping to get some suggestions as to either a place to look, or a slick way of doing this.

like image 575
turbo_laser Avatar asked Sep 03 '15 19:09

turbo_laser


People also ask

How do I create an instance of a class in Scala?

Defining a classThe keyword new is used to create an instance of the class. We call the class like a function, as User() , to create an instance of the class.

Can we create object without class in Scala?

Scala doesn't have static methods or fields. Instead you should use object . You can use it with or without related class.

How do you create an object class in Scala?

Instead, Scala has singleton objects. A singleton is a class that can have only one instance, i.e., Object. You create singleton using the keyword object instead of class keyword. Since you can't instantiate a singleton object, you can't pass parameters to the primary constructor.

What is a difference between a class and an object in Scala?

Difference Between Scala Classes and Objects Definition: A class is defined with the class keyword while an object is defined using the object keyword. Also, whereas a class can take parameters, an object can't take any parameter. Instantiation: To instantiate a regular class, we use the new keyword.


1 Answers

You can use reflections as follows:

def actionBuilder(name: String): Action = {
  val action = Class.forName("package." + name + "Action").getDeclaredConstructor().newInstance()
  action.asInstanceOf[Action]
}
like image 92
Philosophus42 Avatar answered Nov 02 '22 10:11

Philosophus42