欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Java创建对象的几种方法

程序员文章站 2024-03-11 14:50:43
有时候,也可能碰到这样面试题,如: java创建对象有哪几种方法? 除了new之外,java创建对象还有哪几种方式? 本文结合例子,给出几种java创建对象的方法,h...

有时候,也可能碰到这样面试题,如:

java创建对象有哪几种方法?

除了new之外,java创建对象还有哪几种方式?

本文结合例子,给出几种java创建对象的方法,here we go~~~~

使用new创建

这是最常用的一种。如:

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;

  /**书名*/
  private string name;

  /**作者*/
  private list<string> authors;

  /**isbn*/
  private string isbn;

  /**价格*/
  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创建对象
     */
    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()

如果要调用clone方法,那么该object需要实现cloneable接口,并重写clone()方法。

修改后的book类如下:

package test;

import java.io.serializable;
import java.util.list;

/**
 * @author wangmengjun
 *
 */
public class book implements serializable, cloneable {

  private static final long serialversionuid = -6212470156629515269l;

  /**书名*/
  private string name;

  /**作者*/
  private list<string> authors;

  /**isbn*/
  private string isbn;

  /**价格*/
  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();
  }

}

测试代码

    /**
     * 1. 使用new创建对象
     */
    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创建对象
     */
    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()

可以指定构造器来创建,如选择第一个构造器创建;也可以指定构造函数参数类型来创建。

    /**
     * 4. 使用constructor.newinstance();
     */
    try {
      //选择第一个构造器创建book
      book book4 = (book) book.class.getconstructors()[0].newinstance();
      //book [name=null, authors=null, isbn=null, price=0.0]
      system.out.println(book4);

      /**
       * 调用指定构造函数创建对象
       */
      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(),其本质是一样的,都采用了反射机制。

使用反序列化

    /**
     * 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();
    }
 

当然了,除了上述几种方式之外,还可以使用jni等方式来创建对象,这边就不一一列举了。

完整的示例代码如下:

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;

  /**书名*/
  private string name;

  /**作者*/
  private list<string> authors;

  /**isbn*/
  private string isbn;

  /**价格*/
  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创建对象
     */
    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创建对象
     */
    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 {
      //选择第一个构造器创建book
      book book4 = (book) book.class.getconstructors()[0].newinstance();
      //book [name=null, authors=null, isbn=null, price=0.0]
      system.out.println(book4);

      /**
       * 调用指定构造函数创建对象
       */
      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();
    }
  }

}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。