I can not write a class, also called java.lang.String

Source: Internet
Author: User
Tags stringbuffer

Http://bbs.itheima.com/thread-51369-1-1.html

OK, but even if you write this class, it's no use.

This question involves the loader's delegate mechanism, in the class loader's structure diagram (below),
Bootstrap is the top-level parent class, Extclassloader is a subclass of the Bootstrap class, Extclassloader is also the Appclassloader parent class
In java.lang.String, for example, when I use this class, the Java virtual opportunity loads the byte code of the Java.lang.String class into memory.

Why load only the Java.lang.String class passed by the system without loading the user-defined java.lang.String class.

When a class is loaded, the parent class loader is used preferentially to load the class that needs to be used. If we have customized this class java.lang.String,
Loads the custom string class, which uses the loader that is Appclassloader, based on the principle of using the parent class loader preferentially,
The Appclassloader loader's parent class is Extclassloader, so the class loader used by the load string is Extclassloader,
However, the class loader Extclassloader did not find the String.class class in the Jre/lib/ext directory. Then use the loader bootstrap of the Extclassloader parent class,
The parent class loader Bootstrap found String.class in the Jre/lib directory Rt.jar and loaded it into memory. This is the delegate mechanism of the ClassLoader.

Therefore, user-defined java.lang.String are not loaded, which means they are not used.

class loader structure diagram. png (72.83 KB, download times: 0)

Download attachments save to album

2013-5-23 16:40 Upload

class loader structure diagram

The http://rainlife.iteye.com/blog/70072 JVM loads classes by ClassLoader the LoadClass () method to load the class, the LoadClass (String name) method:

  Public class<?> loadclass (String name) throws ClassNotFoundException {return
	loadclass (name, false);
    }

The LoadClass (string name) method then calls the LoadClass (string name, Boolean Resolve) method:
-Name-binary name of class
-Resolve-If the argument is true, the class is parsed
Protected synchronized class<?> loadclass (String name, Boolean resolve)
	throws ClassNotFoundException
    {
	//The check if the class has already been loaded
	//JVM specification that ClassLoader can keep the class it loads in the cache if a class has been loaded, Gets
	Class C = findloadedclass (name) directly from the cache;
	if (c = = null) {
	    try {
		if (parent!= null) {
		    c = parent.loadclass (name, false);
		} else {
		    c = findboot STRAPCLASS0 (name);
		}
	    catch (ClassNotFoundException e) {
	        //If still not found, then invoke Findclass into order
	        //To find the Class.
  c = Findclass (name);
	    }
	}
	if (resolve) {
	    resolveclass (c);
	}
	return c;
}

If ClassLoader does not load this class, then call FINDBOOTSTRAPCLASS0:
Private Class FindBootstrapClass0 (String name)
	throws ClassNotFoundException
    {
	check ();
	if (!checkname (name))
	    throw new ClassNotFoundException (name);
	return Findbootstrapclass (name);
    

The method invokes the check () method to determine whether the class has been initialized and, by CheckName (name), to determine whether the class specified by name exists
Last Call Findbootstrapclass (name):
Private native Class Findbootstrapclass (String name)
	throws ClassNotFoundException;

And this findbootstrapclass method is a native method, this is our root loader, this loading method is not written by Java, but C + +, It eventually invokes the native Findbootstrapclass method in the JVM to complete the load of the class.

If none of the above two are found, use Findclass (name) to find the class with the specified name:
Protected class<?> Findclass (String name) throws ClassNotFoundException {
	throw new ClassNotFoundException ( name);


description in JDK5.0:
Finds a class by using the specified binary name. This method should be overridden by the class loader implementation, which loads the class according to the delegate model. After checking the requested class through the parent class loader, this method is called by the LoadClass method. The default implementation throws a ClassNotFoundException.
So, in the custom class, we just need to rewrite findclass ().
Myclassloader class:
 Extends ClassLoader {private String fileName;
    Public Myclassloader (String fileName) {this.filename = filename; } protected class<?> Findclass (String className) throws ClassNotFoundException {Class clazz = This.fin
        Dloadedclass (ClassName);
                if (null = = Clazz) {try {String classfile = Getclassfile (className);
                FileInputStream fis = new FileInputStream (classfile);
                FileChannel Filec = Fis.getchannel ();
                Bytearrayoutputstream BAOs = new Bytearrayoutputstream ();
                Writablebytechannel OUTC = Channels.newchannel (BAOs);
                Bytebuffer buffer = bytebuffer.allocatedirect (1024);
                    while (true) {int i = filec.read (buffer);
                    if (i = = 0 | | | = = = 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 ();
    } return clazz;
            Private byte[] Loadclassbytes (String className) throws ClassNotFoundException {try {
            String classfile = Getclassfile (className);
            FileInputStream fis = new FileInputStream (classfile);
            FileChannel Filec = Fis.getchannel ();
            Bytearrayoutputstream BAOs = new Bytearrayoutputstream ();
            Writablebytechannel OUTC = Channels.newchannel (BAOs);
            Bytebuffer buffer = bytebuffer.allocatedirect (1024);
     while (true) {int i = filec.read (buffer);           if (i = = 0 | | | = = = 1) {break;
                } buffer.flip ();
                Outc.write (buffer);
            Buffer.clear ();
            } fis.close ();
        return Baos.tobytearray ();
        catch (IOException Fnfe) {throw new ClassNotFoundException (ClassName);
        } private String Getclassfile (string name) {StringBuffer sb = new StringBuffer (fileName);
        Name = Name.replace ('. ', File.separatorchar) + ". Class";
        Sb.append (file.separator + name);
    return sb.tostring ();
 }
}

This class defines a class by calling the DefineClass (String name, byte[] B, int off, int len) method:
  Protected final class<?> defineclass (String name, byte[] B, int off, int len)
	throws Classformaterror
    {
  
   return defineclass (name, B, off, Len, null);
    }

  

Note:Myclassloader Load class has a limitation, you must specify . ClassFile, and cannot specify . JarFile. Most of the code in this class is found from the Internet, is from a cow's pen, just do not know where the original post, hope will not be hidden.
Mainclassloader class:
public class Mainclassloader {public
    static void Main (string[] args) {
        try {
            Myclassloader tc = new Myclasslo Ader ("f:\\openlib\\");
            Class C = Tc.findclass ("Test");
            C.newinstance ();
        } catch (ClassNotFoundException e) {
            e.printstacktrace (); 
        } catch (Illegalaccessexception e) {
            E.printstacktrace ();
        } catch (Instantiationexception e) {
            e.printstacktrace ();}}}


Finally, a simple test class:
public class Test
{public
	test () {
		System.out.println ("test");
	}
	public static void Main (string[] args) {
		System.out.println ("Hello World");
	}

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.