java实例化一个对象的方式

时间:2022-08-12 05:26:08
一.new(经过构造函数)
二.反射(经过构造函数)
三.反序列化(不经过构造函数)
四.克隆(不经过构造函数)
 
package com.wen1024;
public class NewInstance {
    public static void main(String[] args) throws Exception {
        //1、使用new的方式------通过有参构造函数
        Customer customer1 = new Customer("张三", 18);
        System.out.println("customer1:" + customer1);
        //2、使用反射------通过无参构造函数
        Customer customer2 = (Customer) Class.forName("com.itheima.Customer").newInstance();
        System.out.println("customer2:" + customer2);
        //3、使用克隆(需要实现Cloneable接口,重写Object类中的clone方法)------不通过构造函数
        Customer customer3 = (Customer) customer1.clone();
        System.out.println("customer3:" + customer3);
    }
}
 
 
 
package com.wen1024;
import java.io.*;
import java.util.Date;
public class Deserialize {
    public static void main(String[] args) throws Exception {
        // 4、通过反序列化创建对象
        //其中的  C:\Users\Administrator\Desktop\serializable.txt 表示存放序列化对象的文件
        //序列化对象
        ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("C:\\Users\\Administrator\\Desktop\\serializable.obj"));
        Customer customer = new Customer("张三", 18);
        System.out.println(customer);
        //写入customer对象
        out.writeObject(customer);
        out.flush();
        out.close();
        //反序列化对象
        ObjectInputStream in = new ObjectInputStream(new FileInputStream("C:\\Users\\Administrator\\Desktop\\serializable.obj"));
        //读取customer对象
        Customer obj = (Customer) in.readObject();
        System.out.println(obj);
        System.out.println(customer == obj);
        in.close();
    }
}