How to instantiate a Scala object using reflection -
i have code uses reflection instantiate java or scala class, allowing user specify name: assume loadit
below hypothetical method defined using this approach.
def getinstance(name:string, jar:string) = { val c:class[_] = loadit(name, jar) // load class jar c.newinstance.asinstanceof[anyref] // return new instance of class }
this works fine if name
scala class, not if object. define object:
object foo
and call as:
getinstance("foo", "somejar.jar")
i error:
java.lang.instantiationexception: foo @ java.lang.class.newinstance(class.java:364)
is there way can instantiate object?
found answer:
refer this link. added following code:
import scala.reflect.runtime.universe._ def getobjectinstance(clsname: string):anyref = { val mirror = runtimemirror(getclass.getclassloader) val module = mirror.staticmodule(clsname) mirror.reflectmodule(module).instance.asinstanceof[anyref] } val c:class[_] = loadit("foo", "somejar.jar") // ok val o = try c.newinstance.asinstanceof[anyref] catch { case i:java.lang.instantiationexception => getobjectinstance("foo") } // works
Comments
Post a Comment