Deep Understanding Java ClassLoader (3)

Source: Internet
Author: User

5.2 Network Class loader

The following is a network class loader that shows how to implement dynamic updates of components through the ClassLoader. The basic scenario is that the Java byte code (. Class) file is stored on the server and the client obtains the byte code and executes it over the network. When there is a version update, you only need to replace the file saved on the server. The class loader makes it easier to implement this requirement.
The class Networkclassloader is responsible for downloading Java class byte code over the network and defining the Java class. Its implementation is similar to Filesystemclassloader.

 PackageClassLoader; ImportJava.io.ByteArrayOutputStream; ImportJava.io.InputStream; ImportJava.net.URL;  Public classNetworkclassloaderextendsClassLoader {PrivateString Rooturl;  PublicNetworkclassloader (String rooturl) {//Specify URL         This. Rooturl =Rooturl; }        //get the byte code of the class@OverrideprotectedClass<?> Findclass (String name)throwsClassNotFoundException {byte[] Classdata =getclassdata (name); if(Classdata = =NULL) {              Throw Newclassnotfoundexception (); } Else {              returnDefineClass (name, Classdata, 0, classdata.length); }      }        Private byte[] Getclassdata (String className) {//bytes of the class read from the networkString Path =Classnametopath (className); Try{URL URL=NewURL (path); InputStream ins=Url.openstream (); Bytearrayoutputstream BAOs=NewBytearrayoutputstream (); intBufferSize = 4096; byte[] buffer =New byte[buffersize]; intBytesnumread = 0; //Read bytes of class file             while((Bytesnumread = ins.read (buffer))! =-1) {baos.write (buffer,0, Bytesnumread); }              returnBaos.tobytearray (); } Catch(Exception e) {e.printstacktrace (); }          return NULL; }        Privatestring Classnametopath (String className) {//get the URL of the class file        returnRooturl + "/" + classname.replace ('. ', '/') + ". Class"; }  }  

After loading a version of a class through networkclassloader, there are generally two ways to use it. The first approach is to use the Java Reflection API. Another approach is to use interfaces. It is important to note that the classes that are downloaded from the server cannot be referenced directly in the client code because the class loader for the client code cannot find these classes. The Java Reflection API allows you to invoke methods of the Java class directly. The way to use an interface is to put the class of the interface in the client, and load the classes from the server that implement the different versions of this interface . These implementation classes are used by the client through the same interface. The way we use interfaces. Examples are as follows:

Client interface:

 Package ClassLoader;      Public Interface versioned {        String getversion ();  }  
 Package ClassLoader;      Public Interface extends versioned {        string Calculate (string expression);  }  

Different versions of classes on the network:

     Com.example;  import   ClassLoader.    ICalculator;  public  class  Calculatorbasic Span style= "color: #0000ff;" >implements   ICalculator {@Override  public   string calculate (string expression) { return   expression; } @Override  public   String GetVersion      { return  "1.0" ; }    }  
     Com.example;  import   ClassLoader.    ICalculator;  public  class  calculatoradvanced implements    ICalculator {@Override  public   string calculate (string expression) { return  "Result is" + expression; } @Override  public   String GetVersion      { return  "2.0" ; }    }  

The process of loading a class on the network on the client:

 PackageClassLoader;  Public classCalculatortest { Public Static voidMain (string[] args) {String URL= "Http://localhost:8080/ClassloaderTest/classes"; Networkclassloader NCL=Newnetworkclassloader (URL); String Basicclassname= "Com.example.CalculatorBasic"; String Advancedclassname= "Com.example.CalculatorAdvanced"; Try{Class<?> clazz = Ncl.loadclass (basicclassname);//load a version of the classICalculator calculator = (ICalculator) clazz.newinstance ();//Creating ObjectsSystem.out.println (Calculator.getversion ()); Clazz= Ncl.loadclass (Advancedclassname);//load another version of the classCalculator =(ICalculator) clazz.newinstance ();          System.out.println (Calculator.getversion ()); } Catch (Exception e) {e.printstacktrace (); }      }    }  

Deep Understanding Java ClassLoader (3)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.