Here I am explaining the full process of creating a jar and then loading a jar dynamically in another project:
Steps to create jar:
- Create a new Project in any IDE(Eclipse).
- Add a Sample class in packages(in my case MyClass).
- Do right-click on the project and then export as jar and give a local path of system location where the jar wants to keep(right-click -> Export -> choose java/jar file -> next ->give path -> finish).
- Then jar will be available at given location.
package newJar.com.example;
public class MyClass {
public MyClass() {
// TODO Auto-generated constructor stub
}
public void helloWorld() {
System.out.println("Hello from the helloWorld");
}
}
Steps to load the jar dynamically:
Create a new project and add below code:
public class CustomClass {
public CustomClass() {
// TODO Auto-generated constructor stub
}
public void getCall(File myJar) {
try {
URLClassLoader loader = new URLClassLoader(new URL[] { myJar.toURI().toURL() },
CustomClass.class.getClass().getClassLoader());
Class classToLoad = Class.forName("newJar.com.example.MyClass", true, loader);
System.out.println(classToLoad);
Method method = classToLoad.getDeclaredMethod("helloWorld");
Object instance = classToLoad.newInstance();
Object result = method.invoke(instance);
} catch (MalformedURLException | ClassNotFoundException | NoSuchMethodException | SecurityException
| InstantiationException | IllegalAccessException | IllegalArgumentException
| InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
File myJar = new File("Path of your jar ");//"D:\\ECLIPSE\\myjar.jar"
CustomClass cls = new CustomClass();
cls.getCall(myJar);
}
}
This is how it can make use of the jar and if the jar is on the server then can give the server path instead of the local path.