天天看點

面試:Java 對象建立有幾種方式!(5種介紹)

作者:程式員的秃頭之路

使用 new 關鍵字

這是建立 Java 對象最常見的方法。通過使用 new 關鍵字調用類的構造函數來建立對象執行個體。

class Dog {
    public Dog() {
        System.out.println("A dog is created");
    }
}

public class Main {
    public static void main(String[] args) {
        Dog dog = new Dog();
    }
}           

使用 Class 類的 newInstance() 方法

通過使用 Class 類的 newInstance() 方法,可以在運作時動态地建立對象。這種方法要求類必須有一個無參構造函數。

class Cat {
    public Cat() {
        System.out.println("A cat is created");
    }
}

public class Main {
    public static void main(String[] args) {
        try {
            Cat cat = (Cat) Class.forName("Cat").newInstance();
        } catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}           

使用 Constructor 類的 newInstance() 方法

通過擷取類的 Constructor 對象,然後使用其 newInstance() 方法來建立對象執行個體。這種方法允許您在運作時動态建立對象,并且可以使用不同的構造函數。

import java.lang.reflect.Constructor;

class Fish {
    public Fish(String name) {
        System.out.println("A fish named " + name + " is created");
    }
}

public class Main {
    public static void main(String[] args) {
        try {
            Constructor<Fish> constructor = Fish.class.getConstructor(String.class);
            Fish fish = constructor.newInstance("Nemo");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}           

使用 clone() 方法

使用 Object 類的 clone() 方法可以建立一個對象的副本。要使用這種方法,類必須實作 Cloneable 接口。

class Sheep implements Cloneable {
    String name;

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

    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }
}

public class Main {
    public static void main(String[] args) {
        Sheep originalSheep = new Sheep("Dolly");
        try {
            Sheep clonedSheep = (Sheep) originalSheep.clone();
            System.out.println("Cloned sheep name: " + clonedSheep.name);
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }
    }
}           

使用反序列化

反序列化是将一個對象的位元組流轉換回對象的過程。當從檔案、資料庫或網絡等來源讀取對象時,可以使用反序列化建立對象。

import java.io.*;

class Person implements Serializable {
    private static final long serialVersionUID = 1L;
    String name;

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

public class Main {
    public static void main(String[] args) {
        // 序列化對象
        Person person = new Person("John");
        try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("person.ser"))) {
            oos.writeObject(person);
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 反序列化對象
        Person deserializedPerson = null;
        try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream("person.ser"))) {
            deserializedPerson = (Person) ois.readObject();
        } catch(IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
        if (deserializedPerson != null) {
            System.out.println("Deserialized person name: " + deserializedPerson.name);
        }
    }
}           
面試:Java 對象建立有幾種方式!(5種介紹)

繼續閱讀