服务器之家

服务器之家 > 正文

Java创建对象的几种方法

时间:2020-07-15 12:01     来源/作者:王孟君

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

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

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

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

使用new创建

这是最常用的一种。如:

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创建对象
 */
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类如下:

 

?
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创建对象
 */
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()完成。

?
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()

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

?
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 {
  //选择第一个构造器创建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(),其本质是一样的,都采用了反射机制。

使用反序列化

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

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

完整的示例代码如下:

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

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

标签:

相关文章

热门资讯

2020微信伤感网名听哭了 让对方看到心疼的伤感网名大全
2020微信伤感网名听哭了 让对方看到心疼的伤感网名大全 2019-12-26
歪歪漫画vip账号共享2020_yy漫画免费账号密码共享
歪歪漫画vip账号共享2020_yy漫画免费账号密码共享 2020-04-07
男生常说24816是什么意思?女生说13579是什么意思?
男生常说24816是什么意思?女生说13579是什么意思? 2019-09-17
沙雕群名称大全2019精选 今年最火的微信群名沙雕有创意
沙雕群名称大全2019精选 今年最火的微信群名沙雕有创意 2019-07-07
玄元剑仙肉身有什么用 玄元剑仙肉身境界等级划分
玄元剑仙肉身有什么用 玄元剑仙肉身境界等级划分 2019-06-21
返回顶部