Convert: class. forname and classloader. loadclass

Source: Internet
Author: User
The class is loaded in three stages: Loading, linking, and initializing, which are defined in 12.2, 12.3, and 12.4 of the Java language specification respectively.
Class. forname (classname)
Actually, it calls class. forname (classname, true,
This. getclass (). getclassloader ()). Note that the second parameter indicates whether the class must be initialized after being loading.
Classloader. loadclass (classname) actually calls classloader. loadclass (name, false). The second parameter indicates whether the class is linked. The difference comes out. The class loaded by class. forname (classname) has been initialized, while the class loaded by classloader. loadclass (classname) has not been linked.
Generally, both methods have the same effect and can load classes. However, if Program Class. forname (name) is required if the class is initialized.
Example
For example, in JDBC programming, we often see this usage, class. forname ("com. MySQL. JDBC. Driver"), if it is replaced
Getclass (). getclassloader (). loadclass ("com. MySQL. JDBC. Driver.
Why? Open Com. MySQL. JDBC. Driver Source code Look,
//
// Register ourselves with the drivermanager
//
Static {
Try {
Java. SQL. drivermanager. registerdriver (New Driver ());
} Catch (sqlexception e ){
Throw new runtimeexception ("can't register driver! ");
}
}
Originally, the driver registers itself in the static block to Java. SQL. drivermanager. The static block is executed during class initialization. Therefore, you can only use class. forname (classname ).

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.