As Java developers, we create a lot of objects every day, but we usually manage systems using dependency injection, like spring to create objects, but there are many ways to create objects: Using the New keyword, the Newinstance method using class classes, Use the Newinstance method of the constructor class, use the Clone method, and use deserialization. Use the New keyword: This is our most common and simplest way to create objects, and in this way we can call any of the awesome functions (parameterless and parametric). For example: Student Student = new Student (); Using the Class class Newinstance method: We can also create objects using the Newinstance method of the class class, which invokes the parameterless constructor to create the object, such as: Student Student2 = (Student) Class.forName ("root path.") Student "). newinstance (); Or: Student stu = Student.class.newInstance (); The Newinstance method of using the constructor class is similar to the Newinstance method of the class, and there is a newinstance method in the Java.lang.relect.Constructor class that can create the object. We can invoke arguments and private constructors through this newinstance method. such as: constructor<student> constructor = Student.class.getInstance (); Student stu = Constructor.newinstance (); These two newinstance methods are what we call reflection, and in fact class's Newinstance method internally invokes the constructor Newinstance method. This is why many frameworks spring, Hibernate, struts, etc. use the latter. How to use clone: whenever we call an object's Clone method, the JVM creates a new object, copies all the contents of the previous object, creates the object with the Clone method, and does not call any constructors. To use the Clone method, we must first implement the Cloneable interface and implement its defined clone method. such as: Student STU2 = <student>stu.clonE (); This is also the application of the prototype model. Using deserialization: When we serialize and deserialize an object, the JVM creates a separate object for us, and when deserialized, the JVM creates the object without invoking any constructors. To deserialize an object, we need to let our class implement the Serializable interface. For example: ObjectInputStream in = new ObjectInputStream (New FileInputStream ("Data.obj")); Student stu3 = (Student) in.readobject ();
As can be seen from the example above, all other methods except those using the New keyword are all converted to invokevirtual (the direct method of creating the object), which is transformed into two calls, new and invokespecial (constructor calls) by the new method.