Java-12.2 Class Object (1)-Introduction
This section describes the Class objects.
Note the following before introduction:
1. Each Class has a Class object generated in the Class loader subsystem of jvm.
2. The class loader subsystem contains the Class Loader chain, but there is only one native loader. The native loader mainly loads trusted classes in the Java API.
3. The class is loaded only when it is used. This is called dynamic loading.
4. Only when the Class is loaded can all objects of the new Class be created.
Since there is no way to prove the previous points, we can only remember the concept. The following example illustrates the last point:
Package com. ray. ch11; public class Test {public static void main (String [] args) {new A (); try {Class. forName (com. ray. ch11. B); // The package name + class name} catch (ClassNotFoundException e) {// TODO Auto-generated catch blocke. printStackTrace () ;}} class A {static {System. out. println (loading A);} public A () {System. out. println (created A) ;}} class B {static {System. out. println (loading B);} public B () {System. out. println (created B );}}Output:
Loading
Created
Loading B
Note: The full name (package name + Class name) of the string after Class. forName is used ).
As you can see from the output, after the create statement is loaded, it proves that the class is first loaded and then the object is created. However, only the Class is used. in forName B, the Class B is actually loaded, and the Class object of B type is referenced (Class B has been created at the same time when Class B is loaded ), without creating any B object.
In addition to Class. forName, you can obtain the reference of Class objects of type B, B's object, and B. getClass (). The following is an example:
package com.ray.ch11;public class Test {public static void main(String[] args) {B b = new B();System.out.println(b.getClass().getName());System.out.println(B.class.getName());}}class B {static {System.out.println(loading B);}public B() {System.out.println(created B);}}
Output:
Loading B
Created B
Com. ray. ch11. B
Com. ray. ch11. B
Summary: This chapter briefly describes the concepts and usage of Class objects. We will continue to introduce the usage of Class objects and some notes.