Java ClassLoader Loading mechanism understanding practical examples

Source: Internet
Author: User

For the Java classloader loading mechanism, we made a simple classloader and successfully loaded the specified class.

No nonsense, just on the code.

 Packagecom.chq.study.cl;ImportJava.io.ByteArrayOutputStream;ImportJava.io.File;ImportJava.io.FileInputStream;Importjava.io.FileNotFoundException;Importjava.io.IOException;ImportJava.nio.ByteBuffer;ImportJava.nio.channels.Channels;ImportJava.nio.channels.FileChannel;ImportJava.nio.channels.WritableByteChannel;/*** @desc Custom ClassLoader, can only load the. class end, to test the Java ClassLoader mechanism*/ Public classChqclassloaderextendsClassLoader {PrivateString FileName;  PublicChqclassloader (String fileName) { This. FileName =FileName; }    protectedClass<?> Findclass (String className)throwsclassnotfoundexception {Class<?> Clazz = This. Findloadedclass (ClassName); if(NULL==clazz) {            Try{String Classfile=Getclassfile (className); System.out.println ("Findclass" +classfile); FileInputStream FIS=NewFileInputStream (Classfile); FileChannel Filec=Fis.getchannel (); Bytearrayoutputstream BAOs=NewBytearrayoutputstream (); Writablebytechannel OUTC=Channels.newchannel (BAOs); Bytebuffer Buffer= Bytebuffer.allocatedirect (1024);  while(true) {                    inti =filec.read (buffer); if(i = = 0 | | i = =-1) {                         Break;                    } buffer.flip ();                    Outc.write (buffer);                Buffer.clear ();                } fis.close (); byte[] bytes =Baos.tobytearray (); Clazz= DefineClass (className, Bytes, 0, bytes.length); } Catch(FileNotFoundException e) {e.printstacktrace (); } Catch(IOException e) {e.printstacktrace (); }        }        returnClazz; }    Privatestring Getclassfile (string name) {StringBuffer SB=NewStringBuffer (fileName); Name= Name.replace ('. ', File.separatorchar) + ". Class"; Sb.append (File.separator+name); returnsb.tostring (); }}
 package   com.chq.study.cl;  /**   * @desc Self Introduction Test interface class, plastic type with the  */ public  interface   ITest { void   self ();}  
 Package com.chq.study.cl; /**  */Publicclass  Test    {publicvoid self () {        System.out.println (this);}    }
 Packagecom.chq.study.cl;/*** @desc Self Introduction Test implementation class*/ Public classTestimplImplementsITest {/*(non-javadoc) * @see com.chq.study.cl.itest#self ()*/@Override Public voidSelf () {System.out.println ("This was from Testimpl instance" + This); }} 
 Packagecom.chq.study.cl;/** * @authorchenqing * @datetime February 4, 2015 PM 4:54:12 * @desc Entry class, call the custom ClassLoader to load the class for validation*/ Public classMainclassloader {/**     * @paramargs*/     Public Static voidMain (string[] args) {Chqclassloader cl=NewChqclassloader ("C:\\workspaces\\myeclipse Professional 2014\\classloader\\bin"); Try{Class<?> clazz = Cl.findclass ("Com.chq.study.cl.Test"); Try {                //execution here throws an exception, validating the ClassLoader's overall accountability mechanismTest cc =(Test) clazz.newinstance ();                Cc.self (); System.out.println ("Belong class Loader:" +Cc.getclass (). getClassLoader (). toString ()); } Catch(instantiationexception e) {e.printstacktrace (); } Catch(illegalaccessexception e) {e.printstacktrace (); } Catch(classcastexception e) {e.printstacktrace (); }                        //ensure output order            Try{Thread.Sleep (100); } Catch(interruptedexception E1) {e1.printstacktrace (); } clazz= Cl.findclass ("Com.chq.study.cl.TestImpl"); Try {                //normal here, bypassing the overall responsibility mechanism through plasticity as a base class.ITest IC =(ITest) clazz.newinstance ();                Ic.self (); System.out.println ("Belong class Loader:" +Ic.getclass (). getClassLoader (). toString ()); } Catch(instantiationexception e) {e.printstacktrace (); } Catch(illegalaccessexception e) {e.printstacktrace (); } Catch(classcastexception e) {e.printstacktrace (); }        } Catch(ClassNotFoundException e) {e.printstacktrace (); }    }}

The results of the final output show that Test & Testimpl are found, but when instantiated, the former fails because of different classloader loads, while the latter is successfully loaded and instantiated by the molded type as the base class.

Findclass C:\workspaces\MyEclipse Professional 2014\classloader\bin\com\chq\study\cl\test.class  Java.lang.ClassCastException:com.chq.study.cl.Test cannot is cast to com.chq.study.cl.Test at    Com.chq.study.cl.MainClassLoader.main (Mainclassloader.java:2014\classloader\bin\com\chq\study\ Cl\testimpl. class  This  Class loader: [Email protected]

Java ClassLoader Loading mechanism understanding practical examples

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.