scalaurlclassloaderdynamic-class-loaders

Loading class through Jars in scala


I am trying to load a class from target Jar, I saw some examples and tried to replicate, but unfortunately i couldn't.

What am I doing wrong here:

import java.io.File
import java.net.{URL, URLClassLoader}

  val jarPathName = "C:\\Users\\Pedro Luis\\IdeaProjects\\Metamorphosis\\test\\typeLoader\\testJars\\DummySimpleClass3.jar"

  val classLoader = new URLClassLoader(Array[URL](new File(jarPathName).toURI.toURL))
  val classToLoad = classLoader.loadClass("DummySimpleClass.scala")
  val method = classToLoad.getDeclaredMethod("printer")
  val instance = classToLoad.newInstance()

  method.invoke(instance)

The class that is inside of jar is the following:

package typeLoader.testJars

class DummySimpleClass {

  def printer(): Unit = println("Hello World!")

}

And the error that I got is:

java.lang.ClassNotFoundException: scala.typeLoader.testJars.DummySimpleClass.scala
  at java.net.URLClassLoader.findClass(URLClassLoader.java:382)
  at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
  at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
  at efeawfew.JavaTest$.<init>(JavaTest.scala:13)

Any ideas?

enter image description here Edited: Added the jar path


Solution

  • According to your screenshot, your JAR file is not valid, it contains .scala file. Actual JAR file must contain .class file.