How can I load a class from a remote server?
Created May 8, 2012
Brandon Rohlfs
The URLClassLoader class was created specifically to facilitate the downloading of classes over a network. Three constructors are provided, the first of which simply takes a URL[] as an argument using the default ClassLoader.
URLClassLoader(URL[] urls) URLClassLoader(URL[] urls, ClassLoader parent) URLClassLoader(URL[] urls, ClassLoader parent, URLStreamHandlerFactory factory)
If the URL or URL's stored within the URL[] end with '/' then a directory is assumed or a .jar file can be specified.
import java.net.URL; import java.net.URLClassLoader; import java.net.MalformedURLException; public class NetworkClassLoader{ public static void main(String[] args){ URLClassLoader urlcl = null; Class c = null; try{ urlcl = new URLClassLoader(new URL[]{new URL("http://www.javacourses.com/classes/test.jar")}); }catch(MalformedURLException me){ System.out.println(me + " is not a valid URL"); } try{ c = urlcl.loadClass("Tester"); }catch(ClassNotFoundException cnf){ System.out.println("Class could not be found"); } try{ Object o = c.newInstance(); }catch(InstantiationException ie){ System.out.println("Could not create an instance of the class"); }catch(IllegalAccessException iae){ } } }