Skip to content

Instantly share code, notes, and snippets.

@brentsowers1
Created March 6, 2014 02:42
Show Gist options
  • Save brentsowers1/9381244 to your computer and use it in GitHub Desktop.
Save brentsowers1/9381244 to your computer and use it in GitHub Desktop.
Creating a new instance of a generic class
class DynamicTestClass() {
def output() {
println("Hello from a dynamically sent class")
}
}
def testFunc[T : Manifest]() : T = {
manifest[T].erasure.newInstance().asInstanceOf[T]
}
val dynamicTestClassInstance = testFunc[DynamicTestClass]()
dynamicTestClassInstance.output()
@Jacke
Copy link

Jacke commented Apr 27, 2014

def instantiate[T](className:String)(args:Any*): T = {
        val clazz = Class.forName(className)
        val constructor = clazz.getConstructors()(0)
        val workArg:Array[AnyRef] = new Array(args.length)
        var i=0
        for(arg <- args){
          workArg(i) = arg match{
            case i:AnyRef => i
            case i:Int => new java.lang.Integer(i)
            case i:Long => new java.lang.Long(i)
            case i:Float => new java.lang.Float(i)
            case i:Double => new java.lang.Double(i)
            case i:Boolean => new java.lang.Boolean(i)
            case i:Char => new java.lang.Character(i)
            case i:Byte => new java.lang.Byte(i)
            case i:Short => new java.lang.Short(i)
            case _ => arg.asInstanceOf[AnyRef]
          }
          i = i + 1
        }
        return constructor.newInstance(workArg:_*).asInstanceOf[T]
    }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment