Java JVM Learning Note Five (practice your own written class loader)

Source: Internet
Author: User

Welcome loading Please indicate Source: Http://blog.csdn.net/yfqnihao

Course Source: http://download.csdn.net/detail/yfqnihao/4866501

In the third and fourth sections we have been emphasizing that class loaders and security managers can be dynamically extended, or that they can be customized by the user, and today we are trying to do this part of the practice, of course, before reading this article, at least read note three.

Let's start with the dynamic extension of a class loader, which is, of course, a relatively small demo, designed to give you a more image concept.

The first step, first define your own class loader, inherit from ClassLoader, rewrite its Findclass method, as for why to do so, if you read the note Three know, parental delegation mode, if the parent can't loadclass, Bootstrap is not loadclass, the JVM will call the ClassLoader object or the Findclass of its subclass object to load.

 Packagecom.yfq.test;ImportJava.io.File;ImportJava.io.FileInputStream;Importjava.io.FileNotFoundException;Importjava.io.IOException; Public classMyclassloaderextendsClassLoader {@OverrideprotectedClass<?> Findclass (String name)throwsClassNotFoundException {byte[] data =Getbytearray (name); if(Data = =NULL) {              Throw Newclassnotfoundexception (); }          returnDefineClass (name, data, 0, data.length); }            Private byte[] Getbytearray (string name) {string FilePath= Name.replace (".", File.separator); byte[] buf =NULL; Try{FileInputStream in=NewFileInputStream (FilePath); BUF=New byte[In.available ()];        In.read (BUF); } Catch(FileNotFoundException e) {e.printstacktrace (); } Catch(IOException e) {e.printstacktrace (); }        returnbuf; }}

The second step is to define a class that is dedicated to being loaded, where we define a static block of code that will be used later.

 Package com.yfq.test;  Public class Testbeloader {    static{        System.out.println ("Testbeloader init");    }      Public void SayHello () {        System.out.println ("Hello");}    }

The third step is to define a public class with a main function entry for validation.

 Packagecom.yfq.test; Public classTestclassloaderdemo { Public Static voidMain (string[] args)throwsinstantiationexception, illegalaccessexception {Class thiscls= Testclassloaderdemo.class; Myclassloader Myclassloader=NewMyclassloader ();        System.out.println (Thiscls.getclassloader ());        System.out.println (Myclassloader.getparent ()); Try {            //load classes with a custom class loader, which is a way to dynamically extendClass cls2 = Myclassloader.loadclass ("Com.yfq.test.TestBeLoader");            System.out.println (Cls2.getclassloader ()); Testbeloader Test=(Testbeloader) cls2.newinstance (); } Catch(ClassNotFoundException e) {e.printstacktrace (); }    }}

Fourth step, view the results of the operation

[Email protected]
[Email protected]
[Email protected]
Testbeloader Init
Description

First output: The class that loads the Testclassloaderdemo is Appclassloder

The second output: Loading Myclassloader loader is also Appclassloader, here also verified our note three, in the same thread, the dynamic connection mode will use the current thread of the class loader to load the required class file, Because the first and second outputs are the object names of the same object

The third output: is the class loader of the Testbeloader, this output verifies that the dynamic connection mode in the parental delegation mode, because Myclassloader is loaded by Appclassloader, So it will delegate its own parent to load the Com.yfq.test.TestBeLoader class, and the load succeeds so it will no longer invoke its own Findclass method, which we have discussed briefly in note three.

Fourth output: If we will testbeloader test= (Testbeloader) cls2.newinstance (), this sentence is dropped, then there will be no fourth output, why?

The loading of a class is broadly divided into three steps, loading, connecting, and initializing. The initialization of this step is the initial allocation of memory when we first created the object, and it is important to note that it is not initialized immediately after the class is load memory.

Java JVM Learning Note Five (practice your own written class loader)

Related Article

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.