Java-12.2 Class Object (3)-. class

Source: Internet
Author: User

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.

 

 

 

 

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.