public class DestroySingleton { public static void main(String[] args) throws Exception { //通过getInstance()获取 Singleton singleton = Singleton.getInstance(); System.out.println("singleton的hashCode:"+singleton.hashCode()); //通过克隆获取 Singleton clob = (Singleton) Singleton.getInstance().clone(); System.out.println("clob的hashCode:"+clob.hashCode()); //通过序列化,反序列化获取 ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(bos); oos.writeObject(Singleton.getInstance()); ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray()); ObjectInputStream ois = new ObjectInputStream(bis); Singleton serialize = (Singleton) ois.readObject(); if (ois != null) ois.close(); if (bis != null) bis.close(); if (oos != null) oos.close(); if (bos != null) bos.close(); System.out.println("serialize的hashCode:"+serialize.hashCode()); //通过反射获取 Constructor<Singleton> constructor = Singleton.class.getDeclaredConstructor(); constructor.setAccessible(true); Singleton reflex = constructor.newInstance(); System.out.println("reflex的hashCode:"+reflex.hashCode()); } }
运行结果:
1 2 3 4 5 6 7 8 9 10 11 12
singleton的hashCode:366712642 clob的hashCode:366712642 serialize的hashCode:366712642 Exception in thread "main" java.lang.reflect.InvocationTargetException at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62) at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) at java.lang.reflect.Constructor.newInstance(Constructor.java:423) at designPatterns.singleton.doublecheck.DestroySingleton.main(DestroySingleton.java:33) Caused by: java.lang.RuntimeException: 已然被实例化一次,不能在实例化 at designPatterns.singleton.doublecheck.Singleton.<init>(Singleton.java:16) ... 5 more