Tuesday, June 14, 2011

Java applet loads jar files at runtime

Using the bellow mechanisum, java applet can load jar file that locate in your local machine. This may very usefull when applet size is huge and applet have modules. By using this technique applet modules can load as jar files from the local machine.

CustomClassLoader.java

public class CustomClassLoader extends URLClassLoader {

public CustomClassLoader(URL[] urls, ClassLoader parent) {
super(urls, parent);
}

//You can set required permission for load jar file, by overriding bellow method
@Override
protected PermissionCollection getPermissions(CodeSource codesource) {
PermissionCollection perms = super.getPermissions(codesource);
perms.add(new java.lang.reflect.ReflectPermission("*", "read,write"));
}
}


............Try to load jar file from applet............


try {

// applet class loader try to load a class in the local machine jar file.
//but applet couldn't find this class inside the applet and throws Exception.

Class c = this.getClass().getClassLoader().loadClass("class_name");
Object loadClass = c.newInstance();

}
catch (ClassNotFoundException ex) {
try {
//location of the jar file
String jarpath = "jar_file_path";
URL jarfile = new URL("jar", "", "file:" + jarpath + "!/");

//Initialize the custom class loader
CustomClassLoader cl = new CustomClassLoader(new URL[]{jarfile}, Thread.currentThread().getContextClassLoader());

//load the class using custom class loader
Class c = cl.loadClass(implClass);
loadClass = c.newInstance();
}
catch (Exception e) {
}
}