ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
**1. 枚举类** ```java public enum SomeEnum { INSTANCE; } ``` **2. 测试** ```java /** * 先测试一下是否实现了单例 */ @Test public void testSomeEnum() { SomeEnum sc1 = SomeEnum.INSTANCE; SomeEnum sc2 = SomeEnum.INSTANCE; //结果输出为true,说明这两个实例其实是一个,实现了单例 System.out.println(sc1 == sc2); } /** * 克隆方式破坏单例 */ /*@Test public void cloneDestroySomeEnum() { SomeEnum sc1 = SomeEnum.INSTANCE; SomeEnum sc2 = sc1.clone(); // Enum类不支持克隆,克隆方式破坏单例失败 } */ /** * 序列化方式破坏单例 */ @Test public void serializableDestroySomeEnum() throws IOException, ClassNotFoundException { SomeEnum sc1 = SomeEnum.INSTANCE; ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("file")); oos.writeObject(sc1); oos.close(); ObjectInputStream ois = new ObjectInputStream(new FileInputStream("file")); SomeEnum sc2 = (SomeEnum) ois.readObject(); //结果输出为true,说明即使通过了序列化,两个还是同一个实例,单例破坏失败 System.out.println(sc1 == sc2); } /** * 反射方式破坏单例 */ @Test public void reflectDestroySomeEnum() throws NoSuchMethodException, IllegalAccessException , InvocationTargetException, InstantiationException { SomeEnum sc1 = SomeEnum.INSTANCE; Class<SomeEnum> cls = SomeEnum.class; //枚举类的私有构造器是不能通过反射去调用,运行该函数会抛出java.lang.NoSuchMethodException异常 //所以反射方式破坏单例失败 Constructor<SomeEnum> cons = cls.getDeclaredConstructor(); cons.setAccessible(true); SomeEnum sc2 = cons.newInstance(); System.out.println(sc1 == sc2); } ```