Java
是面向对象的编程语言,只要使用它,就需要创建对象。Java创建对象有六种方法,实际常用的不会这么多,这里权当是记录一下。
(1)使用new关键字
Pumpkin p1 = new Pumpkin();
(2)反射之Class类newInstance()
Pumpkin p2 = Pumpkin.class.newInstance();
(3)反射之Constructor类的newInstance()
Pumpkin p3 = Pumpkin.class.getDeclaredConstructor().newInstance();
(4)Object对象的clone方法
Pumpkin p4 = (Pumpkin) p1.clone();
注意 Object
类的 clone
方法是 protected
的,在 Override
的时候,可以改成 public
,这样让其它所有类都可以调用。
注意浅拷贝和深拷贝。
(5)反序列化
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("object.bin")); oos.writeObject(p1); oos.close(); ObjectInputStream ois = new ObjectInputStream(new FileInputStream("object.bin")); Pumpkin p5 = (Pumpkin) ois.readObject(); ois.close();
必须要实现 Serializable
接口;
需要注意哪些字段可序列化,哪些字段不会被序列化,如何控制;
注意 serialVersionUID
的作用;
了解 Externalizable
的不同之处。
(6)使用Unsafe类
Field f = Unsafe.class.getDeclaredField("theUnsafe"); f.setAccessible(true); Unsafe unsafe = (Unsafe) f.get(null); Pumpkin p6 = (Pumpkin) unsafe.allocateInstance(Pumpkin.class);
很少用的方法,一般不用了解这个方法。
示例代码如下:
package com.pkslow.basic; import sun.misc.Unsafe; import java.io.*; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; public class CreateObject { public static class Pumpkin implements Cloneable, Serializable { public Pumpkin(){ System.out.println("Constructor called"); } @Override public Object clone() throws CloneNotSupportedException { return super.clone(); } } public static void main(String[] args) throws IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException, CloneNotSupportedException, IOException, ClassNotFoundException, NoSuchFieldException { System.out.println("---start---"); System.out.println("(1) new"); Pumpkin p1 = new Pumpkin(); System.out.println("(2) Class newInstance"); Pumpkin p2 = Pumpkin.class.newInstance(); System.out.println("(3) Constructor newInstance"); Pumpkin p3 = Pumpkin.class.getDeclaredConstructor().newInstance(); System.out.println("(4) clone"); Pumpkin p4 = (Pumpkin) p1.clone(); System.out.println("(5)Serialization"); ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("object.bin")); oos.writeObject(p1); oos.close(); ObjectInputStream ois = new ObjectInputStream(new FileInputStream("object.bin")); Pumpkin p5 = (Pumpkin) ois.readObject(); ois.close(); System.out.println("(6) Unsafe"); Field f = Unsafe.class.getDeclaredField("theUnsafe"); f.setAccessible(true); Unsafe unsafe = (Unsafe) f.get(null); Pumpkin p6 = (Pumpkin) unsafe.allocateInstance(Pumpkin.class); System.out.println("---end---"); } }
输出结果如下:
---start--- (1) new Constructor called (2) Class newInstance Constructor called (3) Constructor newInstance Constructor called (4) clone (5)Serialization (6) Unsafe ---end---
所以会执行构造函数的有:new关键字、两种反射;
不会执行构造函数的有:clone、序列化、Unsafe类。
要学会生产对象,也要学会管理对象、回收对象。
欢迎访问 南瓜慢说 www.pkslow.com 获取更多精彩文章!
欢迎关注微信公众号< 南瓜慢说 >,将持续为你更新...