Question

Using something like one-jar or sbt-assembly, what is the correct way to dynamically load a class from a fat jar? Single jar example:

val loader = new  URLClassLoader(Array(new File(jarName).toURI.toURL), this.getClass().getClassLoader())
var classToLoad = Class.forName (pluginName, true, loader)
var method = classToLoad.getDeclaredMethod (methodName)
var instance = classToLoad.newInstance ()
var result = method.invoke (instance)
Console.println("Result: " + result)

This works fine for my package made jar, but if I create it via one-jar or assembly, it gets a java.lang.ClassNotFoundException exception. Do I need a custom class loader (and if so, where is it?) Or is there a special syntax needed on the class or package name?

Thanks!

-Greg

(Example in Scala, but more than happy with a Java example!)

Was it helpful?

Solution

There might be a mistake with the jar path. If you want to load class foo.bar.Clazz, you should be able to find file foo/bar/Clazz.class in the fat jar file.

I can use your approach above to load any class from a fat jar created with sbt-assembly without problem.

Try using the absolute file path. Verify that new File(jarName).isFile returns true.

The URLClassLoader requires that the classes are directly accessible inside the jar. Nested jars are not supported.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top