Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save diversit/baad53f65bedae32b9f2 to your computer and use it in GitHub Desktop.
Save diversit/baad53f65bedae32b9f2 to your computer and use it in GitHub Desktop.
Dynamically create an instance of a class using variable arguments.
/**
* 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