Custom ClassLoader for dynamic loading

Source: Internet
Author: User

Different ClassLoader load the same class that will be considered by the JVM to be different classes

To achieve thermal loading, there are several principles to keep in mind:

    1. Instantiate a new ClassLoader every time

    2. Dynamically loading class files, such as Rul or files, etc.

    3. The class that is recorded uses reflection to make a method call, or a call back to an interface.


Let's look at an example:

First, define a called Simple class Appobject:

Package Com.dataguru.jvm.classloader;public class Appobject {public void SayHello () {System.out.println ("Hello 1.");}}

Then customize a classloader subclass of Hotclassloader:

package com.dataguru.jvm.classloader;import java.io.bytearrayoutputstream;import  java.io.ioexception;import java.io.inputstream;import java.lang.class;import  java.lang.classloader;import java.lang.classnotfoundexception;import java.lang.override;import  java.lang.string;import java.lang.system;public class hotclassloader extends  Classloader {public hotclassloader ()  {// TODO Auto-generated constructor  Stub}public hotclassloader (CLASSLOADER&NBSP;CL)  {super (CL);} @Overridepublic  class<?> loadclass (string name,boolean resolve)  throws  classnotfoundexception { {// first, check if the class has  already been loaded class<?> re = null; try{ re =  Findclass (name);  }catch (securityexception se) { system.out.println (Se.getmessage ());  }    if (re == null) {         System.out.println ("Unable to load class:" +name+ "  need to request parent loader");         return  super.loadclass (name,resolve);    }    return re;     }} @Overrideprotected  class<?> findclass (string name)  throws  classnotfoundexception {class<?> cl = null;try {byte[] data =  Loadclassbytes (name); Cl = super.defineclass (name, data, 0, data.length); }  catch  (ioexception e)  {e.printstacktrace ();} RETURN&NBSP;CL;} Public static byte[] loadclassbytes (String clazzname)  throws ioexception{string  resourceName =  "/". Concat (Clazzname.replaceall ("[.]",  "/")). Concat (". Class"); System.out.println ("resource location:" +resourcename); inputstream is  = testmain.class.getresourceasstream (resourcename); Bytearrayoutputstream baos = new bytearrayoutputstream (); byte[] bt = new  byte[1024];int l = 0;while ((L = is.read (BT))  > 0 ) {Baos.write (bt,0,l);} Byte[] rst= baos.tobytearray (); Is.close (); Baos.close (); return rst;}}

Finally write the test class to test:

/** * */package com.dataguru.jvm.classloader;import java.lang.reflect.method;/** * @author ShenLi * */public class TestHo tload {/** * @param args * @throws Exception */public static void Main (string[] args) throws Exception {Hotclassloader MC L = Null;while (true) {MCL = new Hotclassloader (); class<?> CLZ = Mcl.loadclass ("Com.dataguru.jvm.classloader.AppObject", true); MCL = new Hotclassloader (); Object o = Clz.newinstance (); System.out.println (o); Method m = O.getclass (). GetMethod ("SayHello", new class[] {}); M.invoke (o, new object[] {}); Thread.Sleep (5000);}}

Note that each time a new ClassLoader instance is generated, it is because a classloader cannot load the same class twice, otherwise it will be an error. The generated class instance cannot be directly new Appobject () but is invoked through reflection, or upstream to the interface (not yet tested)


Test output:

Resource Location:/com/dataguru/jvm/classloader/appobject.classresource location:/java/lang/ object.classprohibited Package Name:java.lang cannot load class: Java.lang.Object need to request parent loader [email Protected]resource location:/ java/lang/system.classprohibited Package Name:java.lang cannot load class: Java.lang.System need to request parent Loader resource location:/java/io/ printstream.classprohibited Package Name:java.io cannot load class: Java.io.PrintStream needs to request the parent loader Hello 1.



Save compilation after changing the program to Hello 2

At this point the test program does not exit, but continues the output, but the output changes:

Resource Location:/com/dataguru/jvm/classloader/appobject.classresource location:/java/lang/ object.classprohibited Package Name:java.lang cannot load class: Java.lang.Object need to request parent loader [email Protected]resource location:/ java/lang/system.classprohibited Package Name:java.lang cannot load class: Java.lang.System need to request parent Loader resource location:/java/io/ printstream.classprohibited Package Name:java.io cannot load class: Java.io.PrintStream needs to request the parent loader Hello 2.


After modifying the class repeatedly, you can implement dynamic loading.

Custom ClassLoader for dynamic loading

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.