Java中5种创建对象的方式

众所周知,在Java中,类提供对象的蓝图,您可以从类创建对象。在Java中有许多不同的方法来创建对象。

以下是一些在Java中创建对象的方法:

1、 使用new关键字

使用new关键字是创建对象的最基本方法。这是在java中创建对象的最常见方法。几乎99%的对象都是这样创建的。通过使用这个方法,我们可以调用我们想要调用的任何构造函数(无参数或参数化构造函数)。

复制代码
// Java program to illustrate creation of Object 
// using new keyword 
public class NewKeywordExample 
{ 
    String name = "GeeksForGeeks"; 
    public static void main(String[] args) 
    { 
        // Here we are creating Object of 
        // NewKeywordExample using new keyword 
        NewKeywordExample obj = new NewKeywordExample(); 
        System.out.println(obj.name); 
    } 
} 
复制代码

输出:

GeeksForGeeks

2、使用New Instance

如果我们知道类的名称并且如果它有一个公共的默认构造函数,我们就可以通过Class.forName来创建类的对象。forName实际上在Java中加载类,但不创建任何对象。要创建类的对象,必须使用类的newInstance()方法。

复制代码
// Java program to illustrate creation of Object 
// using new Instance 
public class NewInstanceExample 
{ 
    String name = "GeeksForGeeks"; 
    public static void main(String[] args) 
    { 
        try
        { 
            Class cls = Class.forName("NewInstanceExample"); 
            NewInstanceExample obj = 
                    (NewInstanceExample) cls.newInstance(); 
            System.out.println(obj.name); 
        } 
        catch (ClassNotFoundException e) 
        { 
            e.printStackTrace(); 
        } 
        catch (InstantiationException e) 
        { 
            e.printStackTrace(); 
        } 
        catch (IllegalAccessException e) 
        { 
            e.printStackTrace(); 
        } 
    } 
} 
复制代码

输出:

GeeksForGeeks

3、使用clone()方法

每当对任何对象调用clone()方法时,JVM实际上会创建一个新对象,并将前一个对象的所有内容复制到该对象中。使用clone方法创建对象不会调用任何构造函数
要使用clone()方法,类要实现Cloneable接口并且实现clone()方法。

复制代码
// Java program to illustrate creation of Object 
// using clone() method 
public class CloneExample implements Cloneable 
{ 
    @Override
    protected Object clone() throws CloneNotSupportedException 
    { 
        return super.clone(); 
    } 
    String name = "GeeksForGeeks"; 

    public static void main(String[] args) 
    { 
        CloneExample obj1 = new CloneExample(); 
        try
        { 
            CloneExample obj2 = (CloneExample) obj1.clone(); 
            System.out.println(obj2.name); 
        } 
        catch (CloneNotSupportedException e) 
        { 
            e.printStackTrace(); 
        } 
    } 
} 
复制代码

输出:

GeeksForGeeks

注:

  • 这里我们创建的是现有对象的克隆,而不是任何新对象。
  • 类需要实现可克隆接口,否则将抛出CloneNotSupportedException.

4、使用反序列化

每当我们序列化并反序列化一个对象时,JVM会创建一个单独的对象。在反序列化,JVM不使用任何构造函数来创建对象。
要反序列化对象,我们需要在类中实现可序列化接口。

序列化对象:

复制代码
import java.io.Serializable;
import java.time.LocalDate;

/**
 * @author:crelle
 * @className:Person
 * @version:1.0.0
 * @date:2020/8/15
 * @description:XX
 **/
public class Person implements Serializable {

    private static final Long serialVersionUID = 237898764368L;

    public enum Sex {
        MALE, FEMALE
    }
    private String name;

    private LocalDate birthday;

    private Sex gender;

    private String emailAddress;

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

    public void printPerson() {
      System.out.println(toString());
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public LocalDate getBirthday() {
        return birthday;
    }

    public void setBirthday(LocalDate birthday) {
        this.birthday = birthday;
    }

    public Sex getGender() {
        return gender;
    }

    public void setGender(Sex gender) {
        this.gender = gender;
    }

    public String getEmailAddress() {
        return emailAddress;
    }

    public void setEmailAddress(String emailAddress) {
        this.emailAddress = emailAddress;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", birthday=" + birthday +
                ", gender=" + gender +
                ", emailAddress='" + emailAddress + '\'' +
                ", age=" + age +
                '}';
    }
}
复制代码

 

复制代码

/**
* @author:crelle
* @className:DeserializationExample
* @version:1.0.0
* @date:2020/9/18
* @description:XX
**/
// Java program to illustrate Serializing
// an Object.
import crelle.test.java.auxiliary.beans.Person;

import java.io.*;

class SerializationExample
{

public static void main(String[] args)
{
try
{
Person d = new Person("crelle");
FileOutputStream f = new FileOutputStream("person.txt");
ObjectOutputStream oos = new ObjectOutputStream(f);
oos.writeObject(d);
oos.close();
f.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
 
复制代码

反序列化对象:

复制代码
/**
 * @author:crelle
 * @className:DeserializationExample
 * @version:1.0.0
 * @date:2020/9/18
 * @description:XX
 **/
// Java program to illustrate creation of Object
// using Deserialization.
import crelle.test.java.auxiliary.beans.Person;

import java.io.*;

public class DeserializationExample
{
    public static void main(String[] args)
    {
        try
        {
            Person person;
            FileInputStream f = new FileInputStream("person.txt");
            ObjectInputStream oos = new ObjectInputStream(f);
            person = (Person) oos.readObject();
            System.out.println(person.getName());
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }

    }
}
复制代码

输出:

crelle

5、 使用Constructor类的newInstance()方法:

这类似于类的newInstance()方法。java.lang.reflect.Constructor类中有一个newInstance()方法,可用于创建对象。通过使用此newInstance()方法,它也可以调用参数化构造函数和私有构造函数。
复制代码
// Java program to illustrate creation of Object 
// using newInstance() method of Constructor class 
import java.lang.reflect.*; 

public class ReflectionExample 
{ 
    private String name; 
    ReflectionExample() 
    { 
    } 
    public void setName(String name) 
    { 
        this.name = name; 
    } 
    public static void main(String[] args) 
    { 
        try
        { 
            Constructor<ReflectionExample> constructor 
                = ReflectionExample.class.getDeclaredConstructor(); 
            ReflectionExample r = constructor.newInstance(); 
            r.setName("GeeksForGeeks"); 
            System.out.println(r.name); 
        } 
        catch (Exception e) 
        { 
            e.printStackTrace(); 
        } 
    } 
} 
复制代码

输出:

GeeksForGeeks
posted @   我要去巴萨  阅读(1304)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
点击右上角即可分享
微信分享提示