1. Use the new statement directly
Invokes the constructor of the class to instantiate the object.
public static void Newcreate () {Person person = new Person ("Jack");//Output:create person[jack]! SYSTEM.OUT.PRINTLN (person); Output: [email protected]}
2, the use of reflection mechanism
The constructor is invoked indirectly through the newinstance () method of the Java.lang.Class or Java.lang.reflect.Constructor.
public static void Reflectcreate () throws Exception {constructor<person> CST = Person.class.getDeclaredConstructor (String.class); Person person = cst.newinstance ("Jerry"); Output:create person[jerry]! SYSTEM.OUT.PRINTLN (person); Output: [email protected]}
3. How to Clone objects
The object class has a Clone method, overriding this method to implement cloning, remember that the class must implement the Java.lang.Cloneable interface, otherwise it will explode clonenotsupportedexception exception.
public static void Clonecreate () throws Exception {person person = new Person ("Bob");//Output:create person[bob]! SYSTEM.OUT.PRINTLN (person); Output: [email Protected]person cloneperson = (person) person.clone (); System.out.println (Cloneperson + "" + cloneperson.getname ()); Output: [email protected] Bob}
By cloning the object is not called the constructor, the obtained object also copied the original object name value, the Clone method inside the object is a native method, that is, the local code implementation, directly copy the memory, this copy is shallow copy, The basic data type and string type can be fully copied, but for other complex reference types copied is only a reference, by cloning the object to modify the value of the reference type will affect the original object, if you want to implement a deep copy is slightly modified clone method, specific requirements specific analysis.
4. Deserializing objects
public static void Deserializeobject () throws Exception {Bytearrayoutputstream BAOs = new Bytearrayoutputstream (); O Bjectoutputstream Oos = new ObjectOutputStream (BAOs); person person = new Person ("Marry"); Output:create person[marry]! SYSTEM.OUT.PRINTLN (person); Output: [email protected]oos.writeobject (person); Oos.close (); Bytearrayinputstream Bais = new Bytearrayinputstream (Baos.tobytearray ()); ObjectInputStream ois = new ObjectInputStream (Bais); Person Serializedperson = (person) ois.readobject (); System.out.println (Serializedperson + "" + serializedperson.getname ()); Output: [email protected] marryois.close ();}
We find that this method also does not call the constructor, and also restores the original object's name value.
There are several ways to create objects in Java