java launch jar code example

Example 1: java execute jar from main

java -cp MyJar.jar com.packagename.MainClass [somearg1] [somearg2] [etc]

Example 2: java load jar at runtime

URLClassLoader child = new URLClassLoader(
        new URL[] {myJar.toURI().toURL()},
        this.getClass().getClassLoader()
);
Class classToLoad = Class.forName("com.MyClass", true, child);
Method method = classToLoad.getDeclaredMethod("myMethod");
Object instance = classToLoad.newInstance();
Object result = method.invoke(instance);

Example 3: run jar file

java -jar yourFile.jar

Tags:

Java Example