Java創(chuàng)建對(duì)象的幾種方法
有時(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?@Cacheable注解類(lèi)內(nèi)部調(diào)用失效的解決方案
這篇文章主要介紹了Spring?@Cacheable注解類(lèi)內(nèi)部調(diào)用失效的解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-01-01java實(shí)現(xiàn) 微博登錄、微信登錄、qq登錄實(shí)現(xiàn)代碼
這篇文章主要介紹了java實(shí)現(xiàn) 微博登錄、微信登錄、qq登錄實(shí)現(xiàn)代碼的相關(guān)資料,需要的朋友可以參考下2016-10-10Java日常練習(xí)題,每天進(jìn)步一點(diǎn)點(diǎn)(64)
下面小編就為大家?guī)?lái)一篇Java基礎(chǔ)的幾道練習(xí)題(分享)。小編覺(jué)得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧,希望可以幫到你2021-09-09java ArrayBlockingQueue的方法及缺點(diǎn)分析
在本篇內(nèi)容里小編給大家整理的是一篇關(guān)于java ArrayBlockingQueue的方法及缺點(diǎn)分析,對(duì)此有興趣的朋友們可以跟著學(xué)習(xí)下。2021-01-01關(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