一区二区三区在线-一区二区三区亚洲视频-一区二区三区亚洲-一区二区三区午夜-一区二区三区四区在线视频-一区二区三区四区在线免费观看

服務(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)建對象的幾種方法

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

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

這篇文章主要為大家詳細(xì)介紹了Java創(chuàng)建對象的幾種方法,使用new創(chuàng)建、使用object.clone()創(chuàng)建、使用反序列化創(chuàng)建等,具有一定的參考價值,感興趣的小伙伴們可以參考一下

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

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

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

本文結(jié)合例子,給出幾種Java創(chuàng)建對象的方法,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;
 
  /**價格*/
  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)建對象
 */
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需要實現(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;
 
  /**價格*/
  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)建對象
 */
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)建對象
 */
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ò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ò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)建對象
   */
  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)建對象,這邊就不一一列舉了。

完整的示例代碼如下:

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;
 
  /**價格*/
  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)建對象
     */
    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)建對象
     */
    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ò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)建對象
       */
      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)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持服務(wù)器之家。

延伸 · 閱讀

精彩推薦
主站蜘蛛池模板: 欧美同志video 在线观看 | 好男人免费高清在线观看2019 | 亚洲欧洲网站 | 啪一啪在线视频 | dyav午夜片 | 无限资源在线观看完整版免费下载 | 俄罗斯freeⅹ性欧美 | 亚洲国产成人久久精品影视 | 猫咪色网 | 日韩黄色影视 | 91国内精品线免费播放 | 从后面撕开老师的丝袜动态图 | 亚洲国产高清一区二区三区 | 亚欧有色在线观看免费版高清 | 无限资源在线观看完整版免费下载 | 亚洲国产第一区二区香蕉日日 | 天天色综合6 | 亚偷熟乱区视频在线观看 | 精品无码久久久久久久动漫 | 成人网久久 | 果冻传媒在线播放观看228集 | 欧美精品久久久久久久免费观看 | 国产激情一区二区三区四区 | 经典欧美gifxxoo动态图暗网 | 亚洲精品在线看 | 成人在线视频在线观看 | 日本高清免费中文字幕不卡 | ady成人映画网站官网 | 扒开女人下面使劲桶屁股动漫 | 欧美草逼视频 | 免费视频片在线观看 | 国产伦精一区二区三区视频 | 国产免费精彩视频 | 久久强奷乱码老熟女 | 国色天香社区在线视频播放 | 91在线老师啪国自产 | 日本一区二区高清免费不卡 | 爽爽窝窝午夜精品一区二区 | 国产精品热久久毛片 | 91免费精品国自产拍在线可以看 | 高h巨肉play|