Bullet 1: four methods for creating objects in Java, java4
Java is an object-oriented language and is inevitable. The concept of "object" is the core part of the Java language. Here we will briefly discuss how to create a general object in Java.
To sum up, there are four ways to create an object:
- Use the new Keyword to call the object constructor;
- Use the newInstance () method reflected by Java;
- Use the clone () method of the Object class;
- Use the readObject () method of the object stream ObjectInputStream to read the serialized object;
1. Use the new Keyword
The most common Java object constructor creates an object by calling the constructor provided by the class.
2. Use the newInstance () method
There is a newInstance () method in Java reflection. You can create an object as follows:
- Obtains the Class Object of the Class to be created.
- If you only need to call this Class to have the public access permission and no parameter constructor, you can directly use the Class instance method newInstance ().
- Get the constractor object of the Class Object. Call the Class instance method getDeclaredConstractors () to obtain the array of the constractor object. (Retrieve all constructors and ignore access permission restrictions. The array order is determined by the order in the Code)
- If the called Constractor is private, you need to call the instance method setAccessible (true) of the AccessibleObject class of the Constractor class's parent class to break the access restriction.
- Use the Constractor class's instance method newInstance ().
Sample Code:
1 public class MethodNewInstance {2 3 public static void main (String [] args) throws Exception {4 5 // get Class Object 6 class <?> Clazz = Class. forName ("com. gerrard. create. method_newInstance.ObjectToCreate "); 7 // The newInstance () method of the class object, which can only call the Public parameter-free constructor 8 clazz. newInstance (); 9 10 // get the Constructor object array (private or public Constructor) 11 <?> [] Cons = clazz. getDeclaredConstructors (); 12 cons [1]. newInstance (); 13 cons [2]. newInstance ("Gerrard"); 14 // first, the private constructor cannot access 15 cons [0]. setAccessible (true); 16 cons [0]. newInstance ("Gerrard", "Info"); 17} 18}MethodNewInstance
Note:
- There are three methods for getting Class objects, which are not described here.
- There are four methods to obtain the Constractor object, which are not described here.
3. Use the clone () method
The Object class is a direct or indirect parent class of all classes. The Object class provides the instance method native (), and creates an identical Object based on the given Object. The procedure is as follows:
- You want to use the clone () method to create an object class and implement the Cloneable interface.
- Inside the class, rewrite the clone () method of the Object class.
Sample Code:
1 public class ObjectToCreate implements Cloneable {2 3 // rewrite the clone () method of the Object class (native METHOD) 4 public ObjectToCreate clone () {5 ObjectToCreate obj = null; 6 try {7 obj = (ObjectToCreate) super. clone (); 8} catch (CloneNotSupportedException e) {9 // This exception will be thrown if the Cloneable interface is not implemented. 10 e. printStackTrace (); 11} 12 return obj; 13} 14}ObjectToCreate
Note:
- If the Cloneable interface is not implemented, a CloneNotSupportedException exception is thrown.
- The access permission for the clone () method provided by the Object class is protected. Therefore, if you do not override the clone () method, you are not authorized to call it.
- The clone () method of the Object class is the native method.
4. Use the deserialization readObject () method
This method consists of two steps:
- Serialize objects and store them in a file.
- Deserialize the object to obtain the class object.
Serialization:
- Class of the object to be serialized to implement the Serializable interface.
- Use the file output stream FileOutputStream to create a file that stores serialized objects.
- Use the instance method writeObject (obj) of the object output stream ObjectOutputStream ).
- Determine whether the class exists, the name is writeReplace (), and the return type is the Object method. If yes, write the return value of this method; otherwise, write the obj Object.
Deserialization:
- Use the file input stream FileInputStream to find the file that stores the serialized object.
- Use the instance method readObject () of the object input stream ObjectInputStream ().
- Determine whether the class exists, the name is readResolve (), and the return type is Object. If this Object is read, otherwise, the Object stream in the deserialization file is used.
Sample Code:
1 public class ObjectToCreate implements Serializable { 2 3 private static final long serialVersionUID = 1L; 4 5 private Object writeReplace(){ 6 return new Integer(1); 7 } 8 9 private Object readResolve(){10 return new Double(2);11 }12 }ObjectToCreate
1 public class MethodSerialable {2 3 public static void main (String [] args) {4 5 // The default path is the project's root path 6 final String fileName = ". /file/serialable.txt "; 7 8 ObjectToCreate o1 = new ObjectToCreate (); 9 10 // serialize 11 try (FileOutputStream fos = new FileOutputStream (fileName ); 12 ObjectOutputStream oos = new ObjectOutputStream (fos);) {13 oos. writeObject (o1); 14} catch (FileNotFoundException e) {15 e. printStackTrace (); 16} catch (IOException e) {17 e. printStackTrace (); 18} 19} 20}MethodSerialable
1 public class MethodAntiSerialable {2 3 public static void main (String [] args) {4 // The default path is the project's root path 5 final String fileName = ". /file/serialable.txt "; 6 Object o2 = null; 7 // deserialization 8 try (FileInputStream fio = new FileInputStream (fileName); ObjectInputStream ois = new ObjectInputStream (fio );) {9 o2 = ois. readObject (); 10} catch (FileNotFoundException e) {11 e. printStackTrace (); 12} catch (IOException e) {13 e. printStackTrace (); 14} catch (ClassNotFoundException e) {15 e. printStackTrace (); 16} 17 System. out. println (o2); 18} 19}MethodAntiSerialable
Note:
- In the class, writeReplace () and readResoleve () are two very special methods. The feature signature must be strictly restricted: The method name is limited, and the number of parameters is limited to 0, the return type must be an Object and cannot be a subclass of the Object. However, different exceptions can be thrown. There are no restrictions on access modifiers, but it is generally recommended to be private to prevent misoperations. The special feature is to set it as a private method. The compiler will not issue a warning when no other method is called.
5. Summary
Four methods for creating objects in Java: the first method is the most commonly used; the second method goes deep into the source code and points to sun. reflect. constructorAccessor class, JDK does not seem to provide the source code for further exploration, but since it is to call the constructor method, like the first method, the created object is stored in Heap) the third method is to implement a specific interface before it can be used, and it is implemented by calling the native method, that is, non-Java code (probably C), that is, the objects produced by this method may not be recycled by GC (my personal idea), because GC is used to reclaim the objects created by Java code, so we should use it with caution. The fourth method in serialization, A specific interface needs to be implemented, but this is not concerned during deserialization. It stores the object in other media and stores the object in the heap during deserialization.