1. Java程序中对象的创建有四种方式:
● 调用new语句创建对象,最常见的一种
● 运用反射手段创建对象,调用java.lang.Class 或者 java.lang.reflect.Constructor 类的newInstance()实例方法
● 调用对象的clone()方法
● 运用序列化手段,调用java.io.ObjectInputStream 对象的 readObject()方法.
2. 四种方式的代码演示,如下:
(1)创建Java工程,如下:
(2)代码如下:
Person.java,如下:
package com.himi.demo; public class Person implements Cloneable { private int age;
private String name; public Person() { }
public Person(int age, String name) {
this.age = age;
this.name = 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;
} @Override
protected Object clone() throws CloneNotSupportedException {
// TODO Auto-generated method stub
return super.clone();
} }
与此同时,Person2.java,如下:
package com.himi.demo; import java.io.Serializable; public class Person2 implements Serializable { private static final long serialVersionUID = 8735345334183008720L;
private int age;
private String name; public Person2() { }
public Person2(int age, String name) {
this.age = age;
this.name = 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;
} @Override
public String toString() {
// TODO Auto-generated method stub
return "name=" + name + ", age=" + age;
} }
测试类,如下:
package com.himi.demo; import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Date; public class TestDemo { public static void main(String[] args) throws Exception {
//1. 使用new构造方法
Person p1 = new Person(23,"Jack");
System.out.println("使用new构造方法:"+p1); //2. 使用反射,默认调用空构造,必须实现,负责报错:InstantiationException
Person p2 = (Person) Class.forName("com.himi.demo.Person").newInstance();
System.out.println("使用反射:"+p2); //3. 使用clone,必须实现Cloneable接口,否则抛出CloneNotSupportedException
Person p3 = (Person) p1.clone();
System.out.println("使用clone:"+p3); //4. 用对象流来实现,前提是对象必须实现 Serializable
System.out.println();
System.out.println("----------用对象流来实现,前提是对象必须实现 Serializable---------");
ObjectOutputStream out = new ObjectOutputStream (new FileOutputStream("p.txt"));
//序列化对象
Person2 obj = new Person2(24,"haobo");
out.writeObject("你好!");
out.writeObject(new Date());
out.writeObject(obj);
out.writeInt(123); //写入基本类型数据
out.close(); //反序列化对象
ObjectInputStream in = new ObjectInputStream(new FileInputStream("p.txt")); System.out.println("obj1=" + (String) in.readObject());
System.out.println("obj2=" + (Date) in.readObject()); Person2 obj1 = (Person2) in.readObject();
System.out.println("obj1=" + obj1); int num = in.readInt();
System.out.println("num=" + num); in.close();
} }
运行结果,如下: