Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass class as value and create Instance

Tags:

scala

I have many classes of a common base trait. I have a function that needs to create a new instance of a instance of one of these classes, but which one is only known at runtime.

Is it possible to pass this class as a parameter and create an instance at runtime in Scala?

I'm not even sure that the answer would be the best approach but currently it's the only thing I can think of.

like image 591
Martin Thurau Avatar asked Jan 14 '13 10:01

Martin Thurau


People also ask

Can you create an instance of a class?

Note: The phrase "instantiating a class" means the same thing as "creating an object." When you create an object, you are creating an "instance" of a class, therefore "instantiating" a class. The new operator requires a single, postfix argument: a call to a constructor.

How do you pass a class object as a parameter?

To pass an object as an argument we write the object name as the argument while calling the function the same way we do it for other variables. Syntax: function_name(object_name); Example: In this Example there is a class which has an integer variable 'a' and a function 'add' which takes an object as argument.

How do you pass a class value?

Values are passed to classes with getter and setter methods like `earn_money()´. Those methods access your objects variables. If you want your class to store another object you have to define a variable for that object in the constructor.

Can we pass class to constructor in Java?

Constructor(s) of a class must have the same name as the class name in which it resides. A constructor in Java can not be abstract, final, static, or Synchronized. Access modifiers can be used in constructor declaration to control its access i.e which other class can call the constructor.


2 Answers

You could pass the value thus:

myFunc(classOf[myObj])

to the method with signature

def myFunc(clazz : AnyRef)={ ...

but this smells bad. You're either looking at implementing a factory pattern, or better still you could use polymorphism and simply do:

myObj.myFunc

since your functionality is predicated on what class is involved.

like image 70
Brian Agnew Avatar answered Oct 24 '22 08:10

Brian Agnew


Same as in Java:

classOf[MyClass].newInstance // calls the constructor without parameters
classOf[MyClass].getConstructor(/* parameter types */).newInstance(/* parameters */)

See Javadoc for Class.

This will work in any Scala version. Scala 2.10 has new reflection libraries, which are aware of Scala concepts.

like image 39
Alexey Romanov Avatar answered Oct 24 '22 08:10

Alexey Romanov