文章目录
- Java有几种方法可以创建对象?
-
-
- 创建对象的五种方法:
-
- 1.通过new申请对象空间(堆空间)
- 2.通过Class类中的newInstance()方法
- 3.通过Constructor类中的newInstance()方法
- 4.通过Object类中的clone()方法
- 5.通过对象的反序列化
-
- 我的学习论坛
Java有几种方法可以创建对象?
创建对象的五种方法:
- 使用 new 调用对象的构造器;
- 使用 Object 类的 clone() 方法;
- 使用 Class 类的 newInstance() 方法;
- 使用 Constructor 类的 newInstance() 方法;
- 使用对象流 ObjectInputStream的readObject()读取序列化对象的方法;
1.通过new申请对象空间(堆空间)
Handsome handsome = new Handsome();
2.通过Class类中的newInstance()方法
Handsome handsome = Handsome.class.newInstance();
3.通过Constructor类中的newInstance()方法
Handsome handsome = Handsome .class.getConstructor().newInstance();
4.通过Object类中的clone()方法
类对象实现Cloneable接口 结构方法不会执行 设计模式—>Prototype原型模式
Handsome handsome1 = new Handsome (""); Handsome handsome2 = (Handsome ) handsome1.clone();
5.通过对象的反序列化
Handsome handsome1 = new Handsome("反序列化一个对象"); // 序列化一个girlFriend ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream("Handsome.obj")); objectOutputStream.writeObject(handsome);
objectOutputStream.close();
// 反序列化出来
ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream("Handsome.obj"));
Handsome handsome2 = (Handsome) objectInputStream.readObject();
objectInputStream.close();
我的学习论坛
HandsomeForum:用Java编写的学习论坛,打造我们自己的圈子!(http://huangjunjie.vip:66) 文章链接:http://huangjunjie.vip:66/blog/read/rwg7mk59r1fj1h80si