激情久久久_欧美视频区_成人av免费_不卡视频一二三区_欧美精品在欧美一区二区少妇_欧美一区二区三区的

服務(wù)器之家:專注于服務(wù)器技術(shù)及軟件下載分享
分類導(dǎo)航

PHP教程|ASP.NET教程|Java教程|ASP教程|編程技術(shù)|正則表達(dá)式|C/C++|IOS|C#|Swift|Android|VB|R語言|JavaScript|易語言|vb.net|

服務(wù)器之家 - 編程語言 - Java教程 - Java創(chuàng)建對(duì)象的幾種方法

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

2020-07-15 12:01王孟君 Java教程

這篇文章主要為大家詳細(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();

示例如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
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;
 
  /**價(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
2
3
4
5
6
7
8
9
/**
 * 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接口,并重寫clone()方法。

修改后的Book類如下:

 

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
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;
 
  /**價(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();
  }
 
}

測試代碼

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
/**
 * 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()完成。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
/**
 * 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)造器來創(chuàng)建,如選擇第一個(gè)構(gòu)造器創(chuàng)建;也可以指定構(gòu)造函數(shù)參數(shù)類型來創(chuàng)建。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
/**
 * 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ī)制。

使用反序列化

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
/**
 * 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等方式來創(chuàng)建對(duì)象,這邊就不一一列舉了。

完整的示例代碼如下:

Book.java

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
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;
 
  /**價(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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
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();
    }
  }
 
}

以上就是本文的全部內(nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持服務(wù)器之家。

延伸 · 閱讀

精彩推薦
主站蜘蛛池模板: 国产成人精品一区二区三区电影 | 黄网站免费观看视频 | 久久欧美亚洲另类专区91大神 | 在线成人免费观看视频 | 精品国产一区二区三区久久久蜜 | 免费高潮在线国 | 久久精品23| 天天曰夜夜操 | 91麻豆蜜桃一区二区三区 | 久久久久在线观看 | 国产精品久久久久久久久久三级 | 国产精品三级a三级三级午夜 | 免费午夜视频在线观看 | 欧美日韩视频第一页 | 第一福利在线 | 欧美日韩激情 | 99影视在线视频免费观看 | 夏目友人帐第七季第一集 | 久草在线免费看 | 国产毛片毛片毛片 | 中文字幕在线观看精品 | 蜜桃网站在线观看 | 成人毛片久久 | 国产精品欧美久久久久一区二区 | 婷婷亚洲一区二区三区 | 色玖玖综合| 全黄裸片武则天一级第4季 偿还电影免费看 | 日韩av成人 | 色婷婷久久久亚洲一区二区三区 | 中文字幕一二三区芒果 | 欧美成人精品一区二区三区 | 91九色蝌蚪国产 | 国产精品久久久久久久四虎电影 | 视频一区二区国产 | 欧美一级α片 | 91免费国产视频 | 性猛aa久久久 | 久久久久久免费 | 91精品国产777在线观看 | 久久一区国产 | 精品国产一区二区三区久久久蜜 |