How to invoke a method in the jar?
We can use URLClassLoader to load classes from a given path.
URL myJar = new File("jar/LibraryA-1.0-SNAPSHOT.jar").toURI().toURL(); URLClassLoader clsLoader = new URLClassLoader( new URL[] {myJar}, this.getClass().getClassLoader() ); Class<?> loadedClass = clsLoader.loadClass("com.sean.liba.Main"); Method method = loadedClass.getDeclaredMethod("print"); Object instance = loadedClass.newInstance(); method.invoke(instance); // Output: Hello World! Let’s look at other use cases. What if you have two jars, and liba.jar deppends on another class in the libb.jar?
Take the above example, the print method has a dependency on the com.
Posted by Sean's Blog on Friday, August 12, 2022