-3

I need to add a jar at run time from path provided in the config file. Let us call it run-time.jar.

My original jar is original.jar. I am importing classes from run-time.jar directly in my original.jar. At compilation time I have a sample version of run-time.jar to help me through compilation issues. I am building a thin jar with out dependencies.

I am planning to use URLClassLoader to load classes at run time. My sample code in original.jar is

// Importing class from run-time.jar
import run.time.Test

class Original {

  public static void main(String[] args) {

    /*Code to load classes from jar file*/

    Test newTest = new Test(); 
    newTest.runTests(); 
  }
}

Will this approach work or is there any suggestion to do it better. Any help is appreciated. Thanks!!

Reference: How should I load Jars dynamically at runtime?

Falcon
  • 69
  • 2
  • 9
  • 1
    Yes: `URLClassLoader` is the way to go. – Maurice Perry Nov 26 '19 at 11:33
  • 1
    The correct way to do this is with [ServiceLoader](https://docs.oracle.com/en/java/javase/13/docs/api/java.base/java/util/ServiceLoader.html). You should not read a .jar file directly to load its classes. – VGR Nov 26 '19 at 17:17

1 Answers1

1

This approach is sometimes used to load JDBC drivers at runtime, you can get some inspiration from this thread: Loading JDBC Driver at Runtime

I suppose to find out whether this works for your jar, just try it out. But I think your classloader hack should work for Java version < 9.

However from a code quality point of view, this is not a very clean solution as I am sure you are aware of. Have you considered looking into OSGi?

SteffenJacobs
  • 402
  • 2
  • 10