Java創建對象的5種方式

實現

package com.mikamo.newclass;

import java.io.Serializable;

public class Employee implements  Serializable {

    private static final long serialVersionUID = -2237531491283515012L;

    private String name;

    public Employee() {

    }

    public Employee(String name) {
        this.name = name;
    }

    public void show(){
        if(name != null){
            System.out.println(name);
        }else{
            System.out.println("employee");
        }
    }

    @Override
    protected Employee clone() throws CloneNotSupportedException {
        return this;
    }
}
package com.mikamo.newclass;

import java.io.*;
import java.lang.reflect.Constructor;

public class Test {

    public static void main(String[] args){
        try {
            //使用new關鍵字構造
            Employee e1 = new Employee();
            e1.show();
            System.out.println("------------------------------------------");
            //只能通過無參構成方法構造
            Employee e2 = Employee.class.newInstance();
            e2.show();
            System.out.println("------------------------------------------");
            //獲取指定的構成方法
            Constructor<Employee> constructor = Employee.class.getConstructor(String.class);
            Employee e3 = constructor.newInstance("luke");
            e3.show();
            System.out.println("------------------------------------------");
            //通過實現clone方法克隆對象
            Employee e4 = e3.clone();
            e4.show();
            System.out.println("------------------------------------------");
            //通過序列化對象寫入到文件,和反序列化讀取對象
            ObjectOutputStream oo = new ObjectOutputStream(new FileOutputStream(new File("D:/employee.txt")));
            oo.writeObject(e1);
            oo.close();
            ObjectInputStream ois = new ObjectInputStream(new FileInputStream(new File("D:/employee.txt")));
            Employee e5 = (Employee)ois.readObject();
            ois.close();
            e5.show();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

結果

employee
------------------------------------------
employee
------------------------------------------
luke
------------------------------------------
luke
------------------------------------------
employee

參考

https://mp.weixin.qq.com/s/3u7dTh-TLA8fVlRvfw9BaA

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章