Skip to content

Instantly share code, notes, and snippets.

@debop
Created January 19, 2013 10:00
Show Gist options
  • Save debop/4571710 to your computer and use it in GitHub Desktop.
Save debop/4571710 to your computer and use it in GitHub Desktop.
인자가 있는 동적 생성
/**
* Generic 수형의 클래스에 대해 지정된 생성자 인자에 해당하는 생성자를 통해 인스턴스를 생성합니다.
*/
def newInstance[T: ClassTag](initArgs: Any*): T = {
if (initArgs == null || initArgs.length == 0)
return newInstance[T]()
val parameterTypes = initArgs.map(getClass(_)).toArray
val constructor = classTag[T].runtimeClass.getConstructor(parameterTypes: _*)
constructor.newInstance(initArgs.map(_.asInstanceOf[AnyRef]): _*).asInstanceOf[T]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment