In depth understanding of the four ways to create objects in Java

  • Call the new statement to create an object
  • Call the clone() method of the object
  • Create objects using reflection
  • Using deserialization

Call the new statement to create an object

// Use the keyword new of java language to create an object and initialize the object data
    MyObject mo = new MyObject() ; 

Call the clone() method of the object

MyObject anotherObject = new MyObject();
MyObject object = anotherObject.clone();

To clone an object using clone() method:
1. The cloned class should implement the clonable interface.
2. The cloned class should override the clone() method.

Prototype mode is mainly used to copy objects, implement an interface (implement clonable interface) and rewrite a method (override the clone method in Object class), that is, the prototype mode is completed.

The copy in prototype mode is divided into "shallow copy" and "deep copy":

  • Shallow copy: copy the values of member variables of value type. For member variables of reference type, only the references are copied, not the referenced objects
  • Deep copy: copy values of member variables of value type and reference objects of member variables of reference type

(the clone method of the Object class will only copy the values of the basic data types in the Object. It will not copy the array, container Object, reference Object, etc., which is a shallow copy. If you want to implement a deep copy, you must copy the array, container Object, reference Object, etc. in the prototype mode.)

Advantages of prototype mode.

  • 1. If creating a new object is complex, you can use the prototype pattern to simplify the object creation process.
  • 2. Using prototype mode to create an Object is much better than directly creating a new Object, because the clone method of Object class is a local method, which directly operates the binary stream in memory, especially when copying large objects.

Usage scenario of prototype mode.

Because of the above advantages, you can consider using the prototype pattern when you need to create similar objects repeatedly.

For example, you need to create objects in a loop. If the object creation process is complex or there are many cycles, using the prototype mode can not only simplify the creation process, but also improve the overall performance of the system.

Create objects using reflection

Let's first introduce reflection:

Definition of reflection

  • Reflection mechanism is to know all the properties and methods of any class at run time; Any method of any object can be called. In java
    As long as the name of the class is given, all the information of the class can be obtained through the reflection mechanism.
  • Reflection mechanism mainly provides the following functions: determining the class of any object at run time; Create objects at run time; Determine the member variables and methods of any class at run time; Call the method of any object at run time; Generate dynamic proxy.

Where is the reflection mechanism used?

There is a line of code in JDBC: class forName(‘com.mysql.jdbc.Driver.class’);// Load the driver class of MySql. This is reflection. Now many frameworks use reflection mechanism. hibernate and struts are implemented by reflection mechanism

Implementation of reflection

The most important and first step to implement reflection in Java is to obtain the Class object. After obtaining the Class object, you can call the corresponding methods through the object to obtain the properties and methods in the Class and call the methods in the Class.

There are four ways to get a Class object:

  • Class.forName("path of class");
  • Class name class
  • Object name getClass()
  • If it is a wrapper Class of basic Type, you can call the Type attribute of the wrapper Class to obtain the Class object of the wrapper Class, Class clazz=
    Integer.TYPE;

Classes that implement Java reflection

  • 1)Class: it represents the classes and interfaces in the running Java application.
  • 2)Field: provides property information about a class or interface, as well as dynamic access permissions to it.
  • 3)Constructor: provides information about a single constructor of a class and access rights to it
  • 4)Method: provides information about a method in a class or interface.

Note: Class is the most important function Class in Java reflection. It is required to implement all the information of the object (including method / attribute / constructor / access permission).

Advantages and disadvantages of reflection mechanism

advantage:

  • (1) It can dynamically obtain the instance of the class at runtime, which greatly improves the flexibility of the program.
  • (2) Combined with Java dynamic compilation, it can achieve incomparably powerful functions.

Disadvantages:

  • (1) The performance of using reflection is low. java reflection is to parse bytecode and parse objects in memory. Solution:

    1. Because the security check of JDK takes a lot of time, close the security check by setAccessible(true) to improve the reflection speed (cancel the check of access control modifier).

    2. When you need to dynamically create an instance of a class many times, the writing method with cache is much faster than that without cache:

    3. The reflectasm tool class can speed up reflection by bytecode generation.

  • (2) Using reflection is relatively unsafe and destroys the encapsulation of the class. You can obtain the private methods and properties of the class through reflection.

Using deserialization

Serializable and Deserialize

Java serialization refers to the process of converting Java objects into byte sequences; Java deserialization refers to the process of restoring byte sequences to Java objects.

Why do I need serialization and deserialization

We know that when two processes communicate remotely, they can send various types of data to each other, including text, pictures, audio, video, etc., and these data will be transmitted on the network in the form of binary sequence. So when two Java processes communicate, can object transfer between processes be realized? The answer is yes. How? This requires Java serialization and deserialization. In other words, on the one hand, the sender needs to convert the Java object into a byte sequence and then transmit it on the network; On the other hand, the receiver needs to recover the Java object from the byte sequence. The basic principle is consistent with network communication. Through a special coding method: write data, encode the object and its internal data, exist in the array or file, and then send it to the destination, decode and read out the data. OK, it will be displayed here for our use.

When we understand why we need Java serialization and deserialization, we naturally think about the benefits of Java serialization. The first advantage is to realize the persistence of data. Through serialization, the data can be permanently saved to the hard disk (usually stored in the file). The second is to realize remote communication by serialization, that is, to transmit the byte sequence of the object on the network.

Object serialization

  • java.io.ObjectOutputStream represents the object output stream, and its writeObject(Object
    obj) method can serialize the obj object specified by the parameter and write the resulting byte sequence to a target output stream. Only objects of classes that implement the Serializable and Externalizable interfaces can be serialized.
  • java.io.ObjectInputStream represents the object input stream. Its readObject() method reads byte sequences from a source input stream, deserializes them into an object, and returns them.
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

/*
 * Serialization stream: store objects into text or transmit them in the network in the same way as a stream; Object -- > stream: ObjectOutputStream
 * Deserialize stream: restore the stream object data in the text file or the stream object data in the network to an object. Stream -- > Object: ObjectInputStream
 */
public class ObjectStreamDemo {
    public static void main(String[] args) throws IOException {
        // Serializing data is actually writing objects to text files
        //write();
        read();
    }

    private static void read() throws IOException {
        // Create deserialized stream object
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream(
                "a.txt"));
        // Read, restore objects
        try {
            Person p = (Person) ois.readObject();
            System.out.println(p.toString());
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        ois.close();
    }

    private static void write() throws IOException {
        // Create serialized stream object
        // public ObjectOutputStream(OutputStream out)
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(
                "a.txt"));
        // create object
        Person p = new Person("java", 20);
        oos.writeObject(p);
        // Release resources
        oos.close();
    }
}
import java.io.Serializable;

/*
 * NotSerializableException To serialize an exception,
 * This class needs to implement an interface: Serializable serialization interface. There is no method in this interface, just as an identification.
 * An interface like this without a method is a tag interface
 * 
 * !!!Each time the class is modified, a new serialization ID value will be generated!, Need to re read, this is the basic method.
 * Find a way to fix the ID of this class and set it manually. In this way, even if the content of the class is modified again, as long as the ID is fixed, it can be guaranteed that it will always match when reading.
 * Add the generated serial version ID, and directly click yellow in the class to add a changed ID value
 */

/*
 * When some member variables do not need to be serialized: how to solve it.
 * Method uses the transient keyword to declare member variables that do not need to be serialized
 */
public class Person implements Serializable{

    /**
     * serialVersionUID
     */
    private static final long serialVersionUID = -9164765814868887767L;

    private String name;
    private transient int age;

    public Person() {
        super();
    }

    public Person(String name, int age) {
        super();
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Person [name=" + name + ", age=" + age + "]";
    }

}

Keywords: Java

Added by Packetrat on Tue, 04 Jan 2022 05:57:54 +0200