In Java, I load external class (in .jar file) by this way:
ClassLoader classLoader = new URLClassLoader(new URL[] {
new File("module.jar").toURI().toURL()});
Class clazz = classLoader.loadClass("my.class.name");
Object instance = clazz.newInstance();
//check and cast to an interface, then use it
if (instance instanceof MyInterface)
...
And it works fine.
====================
Now I want to do the same thing in Scala. I have a trait
named Module
(Module.scala
):
trait Module {
def name: String
}
object Module {
lazy val ModuleClassName = "my.module.ExModule"
}
I write a module extending Module
, then compile it to module.jar
:
package my.module
import Module
object ExModule extends Module {}
Then I load it by this code:
var classLoader = new URLClassLoader(Array[URL](
new File("module.jar").toURI.toURL))
var clazz = classLoader.loadClass(Module.ModuleClassName)
It works fine. But if I create new instance, I get this exception:
java.lang.InstantiationException: my.module.ExModule
If I test it:
clazz.isInstanceOf[Module]
-> always return false
.
So could you help me on this problem?
Edited
I guess it is because ExModule
is an object
(not class
). But when I change it to class
, and classLoader.loadClass(...)
raises a java.lang.NoClassDefFoundError
. I guess it is because ExModule
is extended from a trait
.
I'm confused. Could anyone please help me?
Edited
clazz.isInstanceOf[Class[Module]]//or Class[Byte], or Class[_]...
returns true
.