This is the 8th day of my participation in the August More Text Challenge. For details, see:August is more challenging

An overview of the

Every child learning Java is familiar with objects and their creation (even more so than their own “objects”). But besides creating objects in a new way, what other ways do you know about creating objects? Today we’re going to talk about all the ways Java creates objects.

Objects are created in two broad categories: with constructors called and without modifications called

  • The constructor is called

    • The new method creates an object

    • Create objects by reflection

  • The constructor is not called

    • Create objects using Clone mode

    • Deserialization creates the object

The new method creates an object

Creating objects by new is the most common and commonly used way to create objects. The creation method is simple. It is created directly through the new syntax. The actual creation process is not simple.

Object creation process: 1. Class loading check, first check whether the class has been loaded, if not, perform the corresponding class loading 2. Allocate memory, according to whether the heap memory is neat to determine how to allocate memory. If it is structured, the memory is allocated by means of colliding Pointers (the memory is divided into two parts: used and unused). If not, memory is allocated in the form of a free list (the vm maintains a list of what memory is available) 3. Set the object header. The object header contains two parts of information: it stores the runtime data of the object itself (hash code, GC generational age, lock status flags, etc.), and it is a type pointer that points to its class metadata and determines which class the object is an instance of 5. Execute the init method, and the member variable instantiates the corresponding value

package com.carrywei.bread.object; Public class Computer {// private String type; // Private String color; Public Computer(String type, String color) {system.out.println (" I am "+ color + type +" Computer "); } public static void main(String[] args) {// new method to create object Computer newComputer = newComputer ("MacBook Pro", "deep space Gray "); }}Copy the code

Create objects by reflection

Creating objects by reflection is also a familiar way of creating objects.

The Reflection mechanism in Java means that in the running state of a program, you can construct an object of any class, know the class to which any object belongs, know the member variables and methods of any class, and call the properties and methods of any object.

Code:

/ / a constructor, through reflection to create objects Class CLS = Class. Class.forname (" com.carrywei.bread.object.Com puter "); Class[] paramTypes = { String.class, String.class }; Object[] params = {" ", ""," "}; Constructor con = cls.getConstructor(paramTypes); Computer reflectionComputer = (Computer) con.newInstance(params);Copy the code

Create objects using Clone mode

The core of creating objects by clone method is to implement the Clone method, and then call the clone method created by the original object to create new objects

Public class Computer implements Cloneable{//... @Override public Computer clone(){ try { Computer computer = (Computer) super.clone(); return computer; } catch (CloneNotSupportedException e) { e.printStackTrace(); return null; }} public static void main(String[] args) {Computer newComputer = newComputer ("MacBook Pro", "dark space "); Computer cloneComputer = newComputer.clone(); }}Copy the code

Create objects antisequentially

Java serialization is the process of converting a Java object into a sequence of bytes, and deserialization is the process of restoring a sequence of bytes to a Java object.

An object can be serialized and deserialized if: the class implements the Serializable interface.

Deserialization creates object encoding

ByteArrayOutputStream ByteArrayOutputStream = new ByteArrayOutputStream(); // Create objects by deserialization ByteArrayOutputStream ByteArrayOutputStream = new ByteArrayOutputStream(); ObjectOutputStream ObjectOutputStream = new ObjectOutputStream(byteArrayOutputStream); ObjectOutputStream = new ObjectOutputStream(byteArrayOutputStream); objectOutputStream.writeObject(newComputer); / / from memory deserialization ByteArrayInputStream ByteArrayInputStream = new ByteArrayInputStream (byteArrayOutputStream. ToByteArray ()); ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream); Computer serializeComputer = (Computer) objectInputStream.readObject(); } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); }Copy the code

summary

The complete code for creating an object in the above four ways:

package com.carrywei.bread.object; import java.io.*; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; /** * Created by on 2021/8/8. */ public class implements Cloneable, Serializable {// private String type; // Private String color; Public Computer() {system.out.println (" I am empty Computer "); } public Computer(String type, String color) {system.out.println (" I am "+ color + type +" Computer "); } @Override public Computer clone(){ try { Computer computer = (Computer) super.clone(); return computer; } catch (CloneNotSupportedException e) { e.printStackTrace(); return null; } } public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {Computer newComputer = newComputer ("MacBook Pro", "deep space gray "); Class cls = Class.forName("com.carrywei.bread.object.Computer"); / / by reflection way to create objects System. Out. The println (" -- -- -- -- -- -- -- -- -- -- - by reflection way to create objects -- -- -- -- -- -- -- -- -- "); Class[] paramTypes = { String.class, String.class }; Object[] params = {" ", ""," "}; Constructor con = cls.getConstructor(paramTypes); Computer reflectionComputer = (Computer) con.newInstance(params); / / clone method to create object System. Out. Println (" -- -- -- -- -- -- -- -- -- -- - clone methods to create objects -- -- -- -- -- -- -- -- -- "); Computer cloneComputer = newComputer.clone(); System.out.println(newComputer == cloneComputer); / / create the object by deserialization System. Out. The println (" -- -- -- -- -- -- -- -- -- in deserialization way to create objects -- -- -- -- -- -- -- -- -- -- - "); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); ObjectOutputStream ObjectOutputStream = new ObjectOutputStream(byteArrayOutputStream); ObjectOutputStream = new ObjectOutputStream(byteArrayOutputStream); objectOutputStream.writeObject(newComputer); / / from memory deserialization ByteArrayInputStream ByteArrayInputStream = new ByteArrayInputStream (byteArrayOutputStream. ToByteArray ()); ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream); Computer serializeComputer = (Computer) objectInputStream.readObject(); System.out.println(newComputer == serializeComputer); } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); }}} I'm deep gray MacBook Pro computer -- -- -- -- -- -- -- -- -- -- - by reflection way to create objects -- -- -- -- -- -- -- -- -- I'm a silver millet laptop -- -- -- -- -- -- -- -- -- -- - clone methods to create objects -- -- -- -- -- -- -- -- -- false --------- Create an object by deserializing it ----------- falseCopy the code

From the output, we can see:

  • New and reflection create objects that call constructors, whereas Clone and deserialization do not

  • Clone and deserialization create objects that are not the same as the original objects. These two methods are also used to implement the prototype pattern in the design pattern. (For more on prototyping patterns, read my previous article “Prototyping Patterns: Quickly Copying Existing Instances to Create New Ones”)