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.