Java-12.2 Class Object (3)-. class
In this chapter, we will discuss another way to get the Class Object. class.
1. Example
package com.ray.ch12;public class Test {public static void main(String[] args) {System.out.println(Person.class.getName());}}class Person {static {System.out.println(loading person);}public Person() {System.out.println(creating person);}}
Output:
Com. ray. ch12.Person
In this way, we can get the reference of the Class Object of the Person Class. However, from the output, we can see that, when the reference is obtained, the Person is not loaded into the Class loader.
In fact, the initialization class contains three steps:
(1) load. Find the. class file and load it to the class loader.
(2) link. Allocate space for static properties or methods.
(3) initialization. Initialize static attributes or methods. If a parent class exists, initialize the parent class.
Initialization is performed only when the static method or non-static domain is referenced for the first time.
Since the above Code has not been executed to initialize this step, there will be no printing of information such as loading.
Conclusion: Using. class only gets the Class reference, and Class. forName is initialized in addition to the reference.
package com.ray.ch12;public class Test {public static void main(String[] args) {Class personClass = Person.class;System.out.println(Person.id);try {Class personClass2=Class.forName(com.ray.ch12.Person);} catch (ClassNotFoundException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}class Person {public final static int id = 1;static {System.out.println(loading person);}public Person() {System.out.println(creating person);}}
Output:
1
Loading person
Summary: This chapter ends the use of. class and the difference with Class. forName.