Created
March 21, 2016 07:56
-
-
Save diversit/baad53f65bedae32b9f2 to your computer and use it in GitHub Desktop.
Dynamically create an instance of a class using variable arguments.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Create an instane of a class of type T with given arguments. | |
* | |
* @param args Arguments to create instance with. The order of arguments must match the constructor! | |
* @tparam T Type of class to create. | |
* @return Instance of T constructed with given arguments. | |
*/ | |
def createInstanceOf[T : reflect.runtime.universe.TypeTag](args: Any*): util.Try[T] = { | |
import reflect.runtime.{universe => ru} | |
// Runtime Mirror to be able to do reflection | |
val mirror = ru.runtimeMirror(ReflectionUtil.getClass.getClassLoader) | |
val clazz = ru.typeOf[T].typeSymbol.asClass | |
val classMirror = mirror.reflectClass(clazz) | |
// Expect a single constructor | |
val constructor = ru.typeOf[T].decl(ru.termNames.CONSTRUCTOR).asMethod | |
val constructorMethod = classMirror.reflectConstructor(constructor) | |
util.Try { | |
// create instance using constructors | |
val instance = constructorMethod(args: _*) | |
// need to cast to wanted type | |
instance.asInstanceOf[T] | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment