Five Ways to create (instantiate) objects in Java
1. Creating objects with the new statement is the most common way to create objects.
2, return the object through the factory method, for example: String str = string.valueof (23);
3, the use of reflection means, call Java.lang.Class or Java.lang.reflect.Constructor class newinstance () instance method. such as: Object obj = Class.forName ("Java.lang.Object"). newinstance ();
4, invoke the object's clone () method.
5. Invoke the ReadObject () method of the Java.io.ObjectInputStream object through the I/O stream (including deserialization), such as by means of deserialization.
Package org.whb.test.demo724;
* * Test the use of the Cloneable interface * contains the first and third Methods clone () * However, note that in clone () deep copy and latent copy of the understanding * Instantiate object/class person implements cloneable{
private String name;
private int age;
Public person (String Name,int age) {this.name = name;
This.age = age;
public int getage () {return age;
public void Setage (int age) {this.age = age;
Public String GetName () {return name;
public void SetName (String name) {this.name =name; @Override public Object Clone () throws Clonenotsupportedexception {//TODO auto-generated a stub return sup
Er.clone ();
@Override public String toString () {//TODO auto-generated Method stub return name is: "+name+"; Age is: "+age;
} public class testclone{public static void Main (string[] args) {person P1 = new Person ("Wang Haobo", 25);
System.out.println (p1);
person P2 =null;
try {p2 = (person) p1.clone (); catch (Clonenotsupportedexception e) {//TODO AUto-generated Catch block E.printstacktrace ();
} p2.setname ("Chun Xiang");
P2.setage (24);
System.out.println (p2); }
}
* * * To initialize the object with reflection * Note that there must be constructor * Instantiate class classes and then call the Newinstance () method * * * * Package org.whb.test.demo715;
Class person{private int age;
private String name;
public int getage () {return age;
public void Setage (int age) {this.age = age;
Public String GetName () {return name;
public void SetName (String name) {this.name = name;
The public String toString () {return "Age is:" +this.age+ "name is:" +this.name;
} public class TestClass {public static void main (string[] args) {class<?> c1 = null;
try{C1 = Class.forName ("Org.whb.test.demo715.Person");
}catch (ClassNotFoundException e) {e.printstacktrace ();
person P1 = null;
try {p1 = (person) c1.newinstance ();
catch (Instantiationexception e) {//TODO auto-generated catch block E.printstacktrace ();
catch (Illegalaccessexception e) {//TODO auto-generated catch block E.printstacktrace ();
} p1.setage (12);
P1.setname ("Haobo"); System.out.prIntln (p1); }
}
Package org.whb.test.demo724;
Import java.io.*;
Import Java.util.Date;
/** the serialization and deserialization test class for the * object.
* 1, serialization is what to do. This is simply to save the state of the various objects in memory (i.e. instance variables, not methods) and to read the saved object state again.
Although you can save object states in a variety of ways, Java provides you with a mechanism to preserve the state of objects better than yourself, and that is serialization. * 2, under what circumstances need to serialize a when you want to save the state of the object in memory into a file or database; (b) When you want to use sockets to transfer objects on the network; c when you want to transfer objects via RMI; * 3, related considerations a) serialization,
Saves only the state of the object, regardless of the object's method; b When a parent class is serialized, the subclass is automatically serialized, and no explicit implementation of the serializable interface is required; c) When an object's instance variable refers to another object, serializing the object also serializes the referenced object; D Not all objects can be serialized, as for why not, there are many reasons, such as: 1. Security reasons, such as an object with Private,public field, for an object to be transferred, such as writing to a file, or RMI transmission, etc.
The private domain of this object is not protected during serialization for transmission.
2. Resource allocation reasons, such as the Socket,thread class, if they can be serialized, transmitted or saved, cannot be reallocated to them, and it is not necessary to achieve this. */public class Objectsaver {public static void main (string[] args) throws Exception {ObjectOutputStream out = new Ob
Jectoutputstream (New FileOutputStream ("d:/objectfile.swf"));
Serialization Object Customer customer = new Customer ("Haobo", 24);
Out.writeobject ("Hello!");
Out.writeobject (New Date ()); Out.writeobject (customer);
Out.writeint (123);
Writes the basic type Data out.close ();
Deserialization object ObjectInputStream in = new ObjectInputStream (New FileInputStream ("d:/objectfile.swf"));
System.out.println ("obj1=" + (String) in.readobject ());
System.out.println ("obj2=" + (Date) in.readobject ());
Customer OBJ3 = (customer) in.readobject ();
System.out.println ("obj3=" + obj3);
int obj4 = In.readint ();
System.out.println ("obj4=" + obj4);
In.close (); Class Customer implements Serializable {/** */private static final long Serialversionuid =-881755997994
32325L;
private String name;
private int age;
Public Customer (String name, int age) {this.name = name;
This.age = age;
Public String toString () {return ' name= ' + name + ', age= ' + age;
} * * Obj1= Hello! Obj2=sat June 21:18:19 CST Obj3=name=haobo, age=24 obj4=123 * *
In Java, there are four ways to instantiate a class:
1) using the new operator
2) Newinstance () method of calling class object
3 Call the Clone () method, copy of the existing instance
4) deserialization of classes via ObjectInputStream ReadObject () method
1.classinstance.java
1 import java.io.*;
2
3 class Classinstance implements Cloneable, Serializable {
4 private String str = "Test ...";
5 Public Void Fun () {
6 System.out.println (str);
7 }
8 public classinstance (String str) {
9 System.out.println ("Instantiation of a Parameter class");
Ten this.str + str;
One }
public classinstance () { System.out.println (instantiation of parameterless Class);
This is the public Object clone () . }
18}
2.classinstancetest.java
1 Import java.io.*;
2 Import java.lang.reflect.*; 3 4 public class classinstancetest{5 public static void main (string[] args) throws ClassNotFoundException, Instant Iationexception, 6 illegalaccessexception, Ioexception,invocationtargetexception, nosuchmethodexception{7
Instantiation mode of the first kind 8 classinstance ci01 = new Classinstance ("01");
9 Ci01.fun ();
10 11//Second kind of instantiation mode classinstance ci02 = (classinstance) class.forname ("Classinstance"). newinstance ();
Ci02.fun ();
14 15//Third Kind of instantiation mode classinstance ci03 = (classinstance) ci01.clone ();
Ci03.fun ();
18 19//Fourth instantiation mode of a kind fileoutputstream fos = new FileOutputStream ("ci.tmp");
ObjectOutputStream oos = new ObjectOutputStream (FOS);
Oos.writeobject (CI01);
Oos.close ();
Fos.close ();
FileInputStream fis = new FileInputStream ("ci.tmp"); ObjectInputStreamOIS = new ObjectInputStream (FIS);
Classinstance ci04 = (classinstance) ois.readobject ();
Ois.close ();
Fis.close ();
Ci04.fun ();
System.out.println ("--------------------additional test--------------------");
Classinstance ci05 = null; 36//Extra thinking in the second kind of instantiation, there is no way to implement the method with parameter construction 37//Get class construction information constructor[] ctor = Class.forName ("Clas
Sinstance "). Getdeclaredconstructors (); 39//Find the construction method we need for (int i=0;i<ctor.length;i++) {class[] cl = Ctor[i].getparameterty
PES (); if (Cl.length = 1) {43//Instantiate Object ci05 = (classinstance) class.forname ("Cla
Ssinstance "). GetConstructor (CL). newinstance (New object[]{" 05 "});
Ci05.fun (); 48} 49}
3. Output results
1 instantiation of parameter class
2 test ...
3 instantiation of non-parametric class
4 test ...
5 test ... 01