Java implements hot swap

Source: Internet
Author: User

 Packagetest;ImportJava.io.ByteArrayOutputStream;ImportJava.io.FileInputStream;ImportJava.nio.ByteBuffer;ImportJava.nio.channels.Channels;ImportJava.nio.channels.FileChannel;ImportJava.nio.channels.WritableByteChannel; Public classDynamicloaderextendsClassLoader {PrivateString BaseDir;  PublicDynamicloader (String baseDir) {Super();  This. BaseDir =BaseDir; }    Privatestring Getclassfile (String className) {returnBasedir+classname.replace (".", "/") + ". Class"; }        protectedClass Findclass (String className)throwsclassnotfoundexception {Class clazz= This. Findloadedclass (ClassName); if(NULL==clazz) {            Try{String Classfile=Getclassfile (className); FileInputStream FIS=NewFileInputStream (Classfile); FileChannel Filec=Fis.getchannel (); Bytearrayoutputstream BAOs=NewBytearrayoutputstream (); Writablebytechannel OUTC=Channels.newchannel (BAOs); Bytebuffer Buffer= Bytebuffer.allocatedirect (1024); intCount = 0;  while((count = filec.read (buffer)) > 0) {buffer.flip ();                    Outc.write (buffer);                Buffer.clear ();                } fis.close (); byte[] bytes =Baos.tobytearray (); Clazz= DefineClass (className, Bytes, 0, bytes.length); } Catch(Exception e) {System.out.println ("Can not load class" +classname + "from Dynamicloader."); }        }        returnClazz; }    protected synchronizedClass loadclass (String name,BooleanResolvethrowsClassNotFoundException {//First , check if the class has already been loadedClass re=Findclass (name); if(re==NULL){            return Super. LoadClass (Name,resolve); }        returnre; }}
 Package test;  Public class Worker {    publicvoid  doit () {        System.out.println ("I am version 3 ");}    }
 Packagetest;ImportJava.lang.reflect.Method; Public classHellomain { Public Static voidMain (string[] args)throwsException { while(true) {Dynamicloader loader=NewDynamicloader ("f:\\workspace\\hibernatesrc\\bin\\"); Class Clazz= Loader.loadclass ("Test. Worker "); Object instance=clazz.newinstance (); Method doit= Clazz.getdeclaredmethod ("doit",NULL); Doit.invoke (instance,NULL); Thread.Sleep (2000); }    }}

Ideas:

Create a new custom ClassLoader in Hellomain, and then specify a class file that loads a directory. When loading is not the parent class first, but the subclass precedence mode.

After the custom ClassLoader finds the worker class, the reflection wears the instance.

It is not possible to create worker instances in the Hellomain class with the new keyword, but also to transform the instance of reflection generation into a worker type, because that would cause Appliationclassloader to load the worker class.

If the worker class is loaded by Appliationclassloader, then the new version of the worker can no longer be loaded by application ClassLoader, and there can be only one class with the same name in ClassLoader.

If this is the time for Appliationclassloader to load the old worker class, the classcastexception will appear when the custom ClassLoader loads the new version of the Woker class when the substitution is made.

Because these worker classes come in different classloader, such as the following code will be reported classcastexception.

Dynamicloader loader = new Dynamicloader ("F:workspacehibernatesrcbin");

Class clazz = Loader.loadclass ("Test. Worker ");

Worker instance = (worker) clazz.newinstance ();//classcastexception error
Instance.doit ();

So the worker class can only be loaded with custom ClassLoader. At the same time, the next time you want to run it, create a new custom ClassLoader to load.

Reference http://www.cnblogs.com/princessd8251/articles/3967569.html

Java implements hot swap

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.