I have some code that uses reflection to instantiate a Java or Scala class, allowing a user to specify the name: Assume that loadIt
below is a hypothetical method defined using this approach.
def getInstance(name:String, jar:String) = {
val c:Class[_] = loadIt(name, jar) // load class from the jar
c.newInstance.asInstanceOf[AnyRef] // return new instance of the class
}
This works fine if name
is a Scala class, but not if it is an object. Say I define an object:
object Foo
and call it as:
getInstance("Foo", "someJar.jar")
I get the error:
java.lang.InstantiationException: Foo
at java.lang.Class.newInstance(Class.java:364)
If I do:
getInstance("Foo", "someJar.jar")
I the error:
java.lang.IllegalAccessException: \
Class xyz can not access a member of class Foo$ with modifiers "private"
at sun.reflect.Reflection.ensureMemberAccess(Reflection.java:109)
at java.lang.Class.newInstance(Class.java:373)
Is there any way I can properly instantiate the object?
Aucun commentaire:
Enregistrer un commentaire