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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM