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