Loading Jars While Booting of application from separate external folder
I have faced an
issue with dynamic jars loading to start the service without giving any
classpath in MANIFEST file inside jar file.
I have spent lot
much time on this to get on to the solution, but no luck. I found some info on
stackoverflow pertaining to this. I wanna share that with you today with slight
modifications make use as simple jar file.
Here is the simple
class I wrote and also created a simple jar file for direct usage.
Here is the
Reference for source code url.
You can also
download direct jar file from above URL under "dist" directory.
Sample Class::
package com.rnd.java.bootup;
import java.io.File;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.List;
import org.apache.commons.io.FileUtils;
public class Bootup
{
public void run(String[] args) throws Exception
{
List jars = (List) FileUtils.listFiles(new File(args[1]), null, true);
URL urls[] = FileUtils.toURLs(jars.toArray(new File[jars.size()]));
for (int i = 0; i < urls.length; i++)
{
loadMe(urls[i]);
System.out.println(urls[i]);
}
Object[] arguments = new Object[]{args};
Class classToLoad = Class.forName(args[0]);
Method method = classToLoad.getMethod("main",String[].class);
Object result = method.invoke (null,arguments);
System.out.println(result);
}
private void loadMe(URL url) {
try {
URLClassLoader classLoader = (URLClassLoader)ClassLoader.getSystemClassLoader();
Method method = URLClassLoader.class.getDeclaredMethod("addURL", URL.class);
method.setAccessible(true);
method.invoke(classLoader, url);
} catch (Exception ex) {
ex.printStackTrace();
}
}
/**
* How to use ?
* java -jar bootup.jar com.company.application.mainclass lib main
*
*
* @param args
*/
public static void main(String[] args)
{
if(args.length==0)
{
StringBuilder help = new StringBuilder();
help.append("Usage !!! \n java -jar bootup.jar fullyQualifiedClassName libFolderName method2Call ");
System.out.println(help.toString());
throw new IllegalArgumentException("Wrong number of arguments!!!!");
}else if(args.length==1)
{
args = new String[]{args[0],"lib","main"};
}else if(args.length==2)
{
args = new String[]{args[0],args[1],"main"};
}
try{
new Bootup().run(args);
}catch(Exception e)
{
e.printStackTrace();
}
}
}