Meet java-12.2 Class object from scratch (3)-.class

Source: Internet
Author: User

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

Related Article

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.