How can I load a class from a remote server?

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){
  }
 }
}
0 Comments  (click to add your comment)
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

About | Sitemap | Contact