Five ways to create objects in Java

We always talk about creating a new object without an object. The method of creating an object has become a deep-rooted new method. However, there are many ways to create an object, not only the new method, but also the reflection mechanism and the clone method, Create objects by serialization and deserialization. Here is a summary of several ways to create objects. Let's learn how to create objects in Java.

This is the most common and simplest way to create objects. In this way, we can also call any praise function (non parametric and parametric). For example, student = new student();

This newinstance method calls a parameterless constructor to create an object, such as student student2 = (student) class Forname ("root path. Student") newInstance(); Or: Student stu = student class. newInstance();

3、 Use the newinstance method of the constructor class

This method is very similar to the newinstance method of class, Java lang.relect. There is also a newinstance method in the constructor class to create objects. I

You can call parameterized and private constructors through this newinstance method.

For example: constructor = student class. getInstance(); Student stu = constructor. newInstance();  

These two newinstance methods are what we call reflection. In fact, the newinstance method of class calls the newinstance method of constructor internally.

This is why many frameworks such as spring, hibernate and struts use the latter.

Whenever we call the clone method of an object, the JVM will create a new object and copy all the contents of the previous object. Creating an object with the clone method will not call any constructor. To use the clone method, we must first implement the clonable interface and the clone method it defines. For example: Student stu2 = stu clone(); This is also the application of prototype pattern.

When we serialize and deserialize an object, the JVM will create a separate object for us. During deserialization, the JVM will not call any constructor to create the object. In order to deserialize an object, we need to make our class implement the serializable interface. For example: objectinputstream in = new objectinputstream (New FileInputStream ("data. Obj")); Student stu3 = (Student)in. readObject(); reference resources:

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>