天天看点

面试: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种介绍)

继续阅读