In this chapter we discuss another way to get a 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, you can get a reference to the class object of the person, but from the output we observe that the person is not loaded into the classloader while it is being referenced.
In fact, the initialization class consists of three steps:
(1) load. Locate the. class file and load it into the ClassLoader
(2) links. Allocates space for a static property or method.
(3) Initialize. Initializes a static property or method and, if there is a parent class, initializes the parent class.
Initialization is performed only when a static method or non-static domain is first referenced.
Since the above code has not yet performed to initialize this step, there is no printing of information such as loading.
Conclusion: Using. class only gets the class reference, and Class.forName is initialized, in addition to being referenced.
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 concludes the use of class and its difference from class.forname.
This chapter is here, thank you.
-----------------------------------
Directory
Meet java-12.2 Class object from scratch (3)-.class