The class object is generated in the following way:
1. Class Name: The JVM will use the class loader to load the class into memory (provided that the class has not been loaded into memory) and does not do the initialization of the class. Returns the object of class
2.class.forname ("Class name string") (Note: Class name string is package name + class name) Description: Load class and do static initialization of class, return class object
3. Instance object. GetClass () Description: Static initialization of the class, non-static initialization; Returns a class object that references the object that the runtime really refers to (because: a reference to a child object may be assigned to a reference variable in the parent object)
Use the following procedure to see how the Class object is generated.
public class TestClass {public static void Main (string[] args) {try {//test. Classclass testtypeclass= Testclasstype.class; System.out.println ("Testtypeclass---" +testtypeclass);//Test Class.forName () Class testtypeforname=class.forname (" Testclasstype "); System.out.println ("Testtypeforname---" +testtypeforname);//Test Object.getclass () Testclasstype testtypegetclass= New Testclasstype (); System.out.println ("Testtypegetclass---" +testtypegetclass.getclass ()); } catch (ClassNotFoundException e) {//TODO auto-generated catch Blocke.printstacktrace ();}}} Class testclasstype{//Constructor Public Testclasstype () {System.out.println ("----constructor---");} Static parameter Initialization static{system.out.println ("---static parameter initialization---");} Non-static parameter initialization {SYSTEM.OUT.PRINTLN ("----non-static parameter initialization---");} }
The results of the test are as follows:
Testtypeclass---class Testclasstype
---static parameters are initialized---
Testtypeforname---class Testclasstype
----non-static parameter initialization---
----constructor---
Testtypegetclass---class Testclasstype
According to the results, there are three types of class objects that are generated. and the program prints "static parameter initialization" only once.
We know that static method property initialization is initialized when the class is loaded. Instead of static method property initialization, it is loaded at the time of the new class instance object.
Therefore, this procedure shows that three ways to generate a class object, in fact, there is only one class object. When generating a class object, first determine if the memory is loaded.
So, the process of generating a class object is actually the same:
When we write a new Java class, the JVM will compile it into a class object, stored in a. class file of the same name. At run time, when the object of this class needs to be generated, the JVM checks to see if the class is already loaded in memory. If it is not loaded, the. class file is loaded into memory. If loaded, the instance object is generated according to the class file.
Class name in Java, Class.forName (), getclass () difference