欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Java創(chuàng)建對(duì)象的幾種方法

 更新時(shí)間:2016年12月16日 09:12:42   作者:王孟君  
這篇文章主要為大家詳細(xì)介紹了Java創(chuàng)建對(duì)象的幾種方法,使用new創(chuàng)建、使用object.clone()創(chuàng)建、使用反序列化創(chuàng)建等,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下

有時(shí)候,也可能碰到這樣面試題,如:

Java創(chuàng)建對(duì)象有哪幾種方法?

除了new之外,java創(chuàng)建對(duì)象還有哪幾種方式?

本文結(jié)合例子,給出幾種Java創(chuàng)建對(duì)象的方法,Here we go~~~~

使用new創(chuàng)建

這是最常用的一種。如:

Book book = new Book();

示例如下:

package test;

import java.io.Serializable;
import java.util.List;

/**
 * @author wangmengjun
 *
 */
public class Book implements Serializable{

  private static final long serialVersionUID = -6212470156629515269L;

  /**書(shū)名*/
  private String name;

  /**作者*/
  private List<String> authors;

  /**ISBN*/
  private String isbn;

  /**價(jià)格*/
  private float price;

  public Book() {
  }

  /**
   * @param name
   * @param authors
   * @param isbn
   * @param price
   */
  public Book(String name, List<String> authors, String isbn, float price) {
    this.name = name;
    this.authors = authors;
    this.isbn = isbn;
    this.price = price;
  }

  /**
   * @return the name
   */
  public String getName() {
    return name;
  }

  /**
   * @param name the name to set
   */
  public void setName(String name) {
    this.name = name;
  }

  /**
   * @return the authors
   */
  public List<String> getAuthors() {
    return authors;
  }

  /**
   * @param authors the authors to set
   */
  public void setAuthors(List<String> authors) {
    this.authors = authors;
  }

  /**
   * @return the isbn
   */
  public String getIsbn() {
    return isbn;
  }

  /**
   * @param isbn the isbn to set
   */
  public void setIsbn(String isbn) {
    this.isbn = isbn;
  }

  /**
   * @return the price
   */
  public float getPrice() {
    return price;
  }

  /**
   * @param price the price to set
   */
  public void setPrice(float price) {
    this.price = price;
  }

  /* (non-Javadoc)
   * @see java.lang.Object#toString()
   */
  @Override
  public String toString() {
    return "Book [name=" + name + ", authors=" + authors + ", isbn=" + isbn + ", price="
        + price + "]";
  }

}

    /**
     * 1. 使用new創(chuàng)建對(duì)象
     */
    Book book1 = new Book();
    book1.setName("Redis");
    book1.setAuthors(Arrays.asList("Eric", "John"));
    book1.setPrice(59.00f);
    book1.setIsbn("ABBBB-QQ677868686-HSDKHFKHKH-2324234");
    System.out.println(book1);

使用object.clone()

如果要調(diào)用clone方法,那么該object需要實(shí)現(xiàn)Cloneable接口,并重寫(xiě)clone()方法。

修改后的Book類(lèi)如下:

package test;

import java.io.Serializable;
import java.util.List;

/**
 * @author wangmengjun
 *
 */
public class Book implements Serializable, Cloneable {

  private static final long serialVersionUID = -6212470156629515269L;

  /**書(shū)名*/
  private String name;

  /**作者*/
  private List<String> authors;

  /**ISBN*/
  private String isbn;

  /**價(jià)格*/
  private float price;

  public Book() {
  }

  /**
   * @param name
   * @param authors
   * @param isbn
   * @param price
   */
  public Book(String name, List<String> authors, String isbn, float price) {
    this.name = name;
    this.authors = authors;
    this.isbn = isbn;
    this.price = price;
  }

  /**
   * @return the name
   */
  public String getName() {
    return name;
  }

  /**
   * @param name the name to set
   */
  public void setName(String name) {
    this.name = name;
  }

  /**
   * @return the authors
   */
  public List<String> getAuthors() {
    return authors;
  }

  /**
   * @param authors the authors to set
   */
  public void setAuthors(List<String> authors) {
    this.authors = authors;
  }

  /**
   * @return the isbn
   */
  public String getIsbn() {
    return isbn;
  }

  /**
   * @param isbn the isbn to set
   */
  public void setIsbn(String isbn) {
    this.isbn = isbn;
  }

  /**
   * @return the price
   */
  public float getPrice() {
    return price;
  }

  /**
   * @param price the price to set
   */
  public void setPrice(float price) {
    this.price = price;
  }

  /* (non-Javadoc)
   * @see java.lang.Object#toString()
   */
  @Override
  public String toString() {
    return "Book [name=" + name + ", authors=" + authors + ", isbn=" + isbn + ", price="
        + price + "]";
  }

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

}

測(cè)試代碼

    /**
     * 1. 使用new創(chuàng)建對(duì)象
     */
    Book book1 = new Book();
    book1.setName("Redis");
    book1.setAuthors(Arrays.asList("Eric", "John"));
    book1.setPrice(59.00f);
    book1.setIsbn("ABBBB-QQ677868686-HSDKHFKHKH-2324234");
    System.out.println(book1);

    /**
     * 2. 使用clone創(chuàng)建對(duì)象
     */
    try {
      Book book2 = (Book) book1.clone();
      System.out.println(book2);
    } catch (CloneNotSupportedException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }

使用Class.newInstance()

可以直接使用Class.forName("xxx.xx").newInstance()方法或者XXX.class.newInstance()完成。

    /**
     * 3. 使用Class.newInstance();
     */
    try {
      Book book3 = (Book) Class.forName("test.Book").newInstance();
      System.out.println(book3);

      book3 = Book.class.newInstance();
      System.out.println(book3);
    } catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }

使用Contructor.newInstance()

可以指定構(gòu)造器來(lái)創(chuàng)建,如選擇第一個(gè)構(gòu)造器創(chuàng)建;也可以指定構(gòu)造函數(shù)參數(shù)類(lèi)型來(lái)創(chuàng)建。

    /**
     * 4. 使用Constructor.newInstance();
     */
    try {
      //選擇第一個(gè)構(gòu)造器創(chuàng)建Book
      Book book4 = (Book) Book.class.getConstructors()[0].newInstance();
      //Book [name=null, authors=null, isbn=null, price=0.0]
      System.out.println(book4);

      /**
       * 調(diào)用指定構(gòu)造函數(shù)創(chuàng)建對(duì)象
       */
      book4 = (Book) Book.class.getConstructor(String.class, List.class, String.class,
          float.class).newInstance("New Instance Example", Arrays.asList("Wang", "Eric"),
          "abc1111111-def-33333", 60.00f);
      //Book [name=New Instance Example, authors=[Wang, Eric], isbn=abc1111111-def-33333, price=60.0]
      System.out.println(book4);
    } catch (InstantiationException | IllegalAccessException | IllegalArgumentException
        | InvocationTargetException | SecurityException | NoSuchMethodException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }

使用Class.newInstance()或者Contructor.newInstance(),其本質(zhì)是一樣的,都采用了反射機(jī)制。

使用反序列化

    /**
     * 5. 使用反序列化
     */
    try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("book.dat"));
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream("book.dat"));) {
      oos.writeObject(book1);

      Book book5 = (Book) ois.readObject();
      System.out.println(book5);

    } catch (IOException | ClassNotFoundException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
 

當(dāng)然了,除了上述幾種方式之外,還可以使用JNI等方式來(lái)創(chuàng)建對(duì)象,這邊就不一一列舉了。

完整的示例代碼如下:

Book.java

package test;

import java.io.Serializable;
import java.util.List;

/**
 * @author wangmengjun
 *
 */
public class Book implements Serializable, Cloneable {

  private static final long serialVersionUID = -6212470156629515269L;

  /**書(shū)名*/
  private String name;

  /**作者*/
  private List<String> authors;

  /**ISBN*/
  private String isbn;

  /**價(jià)格*/
  private float price;

  public Book() {
  }

  /**
   * @param name
   * @param authors
   * @param isbn
   * @param price
   */
  public Book(String name, List<String> authors, String isbn, float price) {
    this.name = name;
    this.authors = authors;
    this.isbn = isbn;
    this.price = price;
  }

  /**
   * @return the name
   */
  public String getName() {
    return name;
  }

  /**
   * @param name the name to set
   */
  public void setName(String name) {
    this.name = name;
  }

  /**
   * @return the authors
   */
  public List<String> getAuthors() {
    return authors;
  }

  /**
   * @param authors the authors to set
   */
  public void setAuthors(List<String> authors) {
    this.authors = authors;
  }

  /**
   * @return the isbn
   */
  public String getIsbn() {
    return isbn;
  }

  /**
   * @param isbn the isbn to set
   */
  public void setIsbn(String isbn) {
    this.isbn = isbn;
  }

  /**
   * @return the price
   */
  public float getPrice() {
    return price;
  }

  /**
   * @param price the price to set
   */
  public void setPrice(float price) {
    this.price = price;
  }

  /* (non-Javadoc)
   * @see java.lang.Object#toString()
   */
  @Override
  public String toString() {
    return "Book [name=" + name + ", authors=" + authors + ", isbn=" + isbn + ", price="
        + price + "]";
  }

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

}

CreateObjectExample.java

package test;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.InvocationTargetException;
import java.util.Arrays;
import java.util.List;

/**
 * @author wangmengjun
 *
 */
public class CreateObjectExample {

  public static void main(String[] args) {
    /**
     * 1. 使用new創(chuàng)建對(duì)象
     */
    Book book1 = new Book();
    book1.setName("Redis");
    book1.setAuthors(Arrays.asList("Eric", "John"));
    book1.setPrice(59.00f);
    book1.setIsbn("ABBBB-QQ677868686-HSDKHFKHKH-2324234");
    System.out.println(book1);

    /**
     * 2. 使用clone創(chuàng)建對(duì)象
     */
    try {
      Book book2 = (Book) book1.clone();
      System.out.println(book2);
    } catch (CloneNotSupportedException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }


    /**
     * 3. 使用Class.newInstance();
     */
    try {
      Book book3 = (Book) Class.forName("test.Book").newInstance();
      System.out.println(book3);

      book3 = Book.class.newInstance();
      System.out.println(book3);
    } catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }

    /**
     * 4. 使用Constructor.newInstance();
     */
    try {
      //選擇第一個(gè)構(gòu)造器創(chuàng)建Book
      Book book4 = (Book) Book.class.getConstructors()[0].newInstance();
      //Book [name=null, authors=null, isbn=null, price=0.0]
      System.out.println(book4);

      /**
       * 調(diào)用指定構(gòu)造函數(shù)創(chuàng)建對(duì)象
       */
      book4 = (Book) Book.class.getConstructor(String.class, List.class, String.class,
          float.class).newInstance("New Instance Example", Arrays.asList("Wang", "Eric"),
          "abc1111111-def-33333", 60.00f);
      //Book [name=New Instance Example, authors=[Wang, Eric], isbn=abc1111111-def-33333, price=60.0]
      System.out.println(book4);
    } catch (InstantiationException | IllegalAccessException | IllegalArgumentException
        | InvocationTargetException | SecurityException | NoSuchMethodException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }

    /**
     * 5. 使用反序列化
     */
    try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("book.dat"));
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream("book.dat"));) {
      oos.writeObject(book1);

      Book book5 = (Book) ois.readObject();
      System.out.println(book5);

    } catch (IOException | ClassNotFoundException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }

}

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

  • spring之SpEL表達(dá)式詳解

    spring之SpEL表達(dá)式詳解

    這篇文章主要介紹了spring之SpEL表達(dá)式詳解,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2022-02-02
  • Spring?@Cacheable注解類(lèi)內(nèi)部調(diào)用失效的解決方案

    Spring?@Cacheable注解類(lèi)內(nèi)部調(diào)用失效的解決方案

    這篇文章主要介紹了Spring?@Cacheable注解類(lèi)內(nèi)部調(diào)用失效的解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2022-01-01
  • java實(shí)現(xiàn)  微博登錄、微信登錄、qq登錄實(shí)現(xiàn)代碼

    java實(shí)現(xiàn) 微博登錄、微信登錄、qq登錄實(shí)現(xiàn)代碼

    這篇文章主要介紹了java實(shí)現(xiàn) 微博登錄、微信登錄、qq登錄實(shí)現(xiàn)代碼的相關(guān)資料,需要的朋友可以參考下
    2016-10-10
  • Java日常練習(xí)題,每天進(jìn)步一點(diǎn)點(diǎn)(64)

    Java日常練習(xí)題,每天進(jìn)步一點(diǎn)點(diǎn)(64)

    下面小編就為大家?guī)?lái)一篇Java基礎(chǔ)的幾道練習(xí)題(分享)。小編覺(jué)得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧,希望可以幫到你
    2021-09-09
  • java ArrayBlockingQueue的方法及缺點(diǎn)分析

    java ArrayBlockingQueue的方法及缺點(diǎn)分析

    在本篇內(nèi)容里小編給大家整理的是一篇關(guān)于java ArrayBlockingQueue的方法及缺點(diǎn)分析,對(duì)此有興趣的朋友們可以跟著學(xué)習(xí)下。
    2021-01-01
  • Java 線(xiàn)程池全面總結(jié)與詳解

    Java 線(xiàn)程池全面總結(jié)與詳解

    在一個(gè)應(yīng)用程序中,我們需要多次使用線(xiàn)程,也就意味著,我們需要多次創(chuàng)建并銷(xiāo)毀線(xiàn)程。而創(chuàng)建并銷(xiāo)毀線(xiàn)程的過(guò)程勢(shì)必會(huì)消耗內(nèi)存。而在Java中,內(nèi)存資源是及其寶貴的,所以,我們就提出了線(xiàn)程池的概念
    2021-10-10
  • 深入理解Java設(shè)計(jì)模式之裝飾模式

    深入理解Java設(shè)計(jì)模式之裝飾模式

    這篇文章主要介紹了JAVA設(shè)計(jì)模式之裝飾模式的的相關(guān)資料,文中示例代碼非常詳細(xì),供大家參考和學(xué)習(xí),感興趣的朋友可以了解下
    2021-11-11
  • JAVA多線(xiàn)程中join()方法的使用方法

    JAVA多線(xiàn)程中join()方法的使用方法

    雖然關(guān)于討論線(xiàn)程join()方法的博客已經(jīng)非常極其特別多了,但是前幾天我有一個(gè)困惑卻沒(méi)有能夠得到詳細(xì)解釋?zhuān)?dāng)系統(tǒng)中正在運(yùn)行多個(gè)線(xiàn)程時(shí),join()到底是暫停了哪些線(xiàn)程,所以本文詳細(xì)解釋一下希望能幫助到和我有相同困惑的同學(xué)
    2021-05-05
  • 關(guān)于springmvc報(bào)錯(cuò)404的問(wèn)題

    關(guān)于springmvc報(bào)錯(cuò)404的問(wèn)題

    這篇文章主要介紹了關(guān)于springmvc報(bào)錯(cuò)404的問(wèn)題,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2021-03-03
  • Java Map.get()返回指定鍵所映射的值

    Java Map.get()返回指定鍵所映射的值

    這篇文章主要介紹了Java Map.get()返回指定鍵所映射的值,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2021-03-03

最新評(píng)論