Java
是面向对象的编程语言,只要使用它,就须要建立对象。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方法ide
Pumpkin p4 = (Pumpkin) p1.clone();
注意Object
类的clone
方法是protected
的,在Override
的时候,能够改为public
,这样让其它全部类均可以调用。函数
注意浅拷贝和深拷贝。code
(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
接口;接口
须要注意哪些字段可序列化,哪些字段不会被序列化,如何控制;get
注意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获取更多精彩文章!
欢迎关注微信公众号<南瓜慢说>,将持续为你更新...
多读书,多分享;多写做,多整理。