Method of generating objects Compare

xiaoxiao2021-03-06  44

This is a summary of some experience in my study. I hope that everyone will give advice, and I hope to help some friends interested in this issue. There are at least three ways in Java to generate an object, new, class.Forname (String ClassName), and ClassLoader.LoadClass (String Name). Let us analyze and compare them. 1. Generate objects with keywords: This is the most common way, such as New String ("Hello") The feature of generating objects is that the class of this object must be compiled, if there is no special Reasons and requirements, this is the first choice for us to generate an object; 2, class.Forname (String classname). For example, Class C = Class.Forname ("com.company.jdbc.driver); this method is characterized by inclusion in ClassPath when compiling, and can be delayed to ClaSpath. When the typical use of this method is loaded with a JDBC driver. Because different databases have different JDBC drivers, the application that needs to get some database connection may need to be run when it is a database that is connected to which the database driver is loaded with this way. And this uses a connection pool program that facilitates a general database, because a database connection pool does not need to be a class of drivers for various databases when compiling; 3. ClassLoader.loadClass (String name); this method is more Flexible, it can not only load classes from ClassPath, but also load classes by customizing a ClassLoader at runtime. For example, you can load classes from an HTTP or FTP server, which can be loaded from any BYTE []. If we write a MyclassLoadLoader Extends ClassLoader, then we can make it a good behavior we look forward to the Protected Class Findclass (String Name) method in the parent class, ClassLoad's LoadClass method calls Findclass to come A Class type object, and FindClass can construct a Class type object by calling Class DefineClass (String Name, Byte [] B, INT OFF, INT LEN). This method is characterized by that this class does not need this class in ClassPath even if it is run.

转载请注明原文地址:https://www.9cbs.com/read-73967.html

New Post(0)