Thursday, July 5, 2012

URLClassLoader and reloading a class from the web example


Reload jar from remote example
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;

public class UrlJarReloader {

public static void main(String[] args) {
Runnable r = new Runnable() {
@Override
public void run() {
while (true) {
reloadJarFile();
}
}

private void reloadJarFile() {
try {
System.out.println(" -- Reloading the jar file from the web !");
   String classToLoad = "org.apache.commons.lang3.StringUtils";

   URL jarUrl = new URL("jar:http://archiva/archiva/repository/internal/org/apache/commons/commons-lang3/3.1/commons-lang3-3.1.jar!/");
   URLClassLoader cl = new URLClassLoader(new URL[] {jarUrl}, null);
   Class loadedClass = cl.loadClass(classToLoad);
   
   Method method = loadedClass.getMethod("trim", new Class[] {java.lang.String.class});
   Object reloadMe = loadedClass.getConstructor().newInstance();
   String trimmedString = (String) method.invoke(reloadMe, new Object[]{"           1 2 3 4 5 6          "});
System.out.println(" -- Trimmed string is : {" + trimmedString + "}");
} catch (Exception e) {
e.printStackTrace();
}
}
};
startReloader(r);
}

private static void startReloader(Runnable r) {
try {
Thread reloader = new Thread(r);
reloader.start();
reloader.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

No comments:

Post a Comment