Path: blob/master/test/jdk/java/io/Serializable/nestedReplace/NestedReplace.java
41153 views
/*1* Copyright (c) 1999, 2019, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation.7*8* This code is distributed in the hope that it will be useful, but WITHOUT9* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or10* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License11* version 2 for more details (a copy is included in the LICENSE file that12* accompanied this code).13*14* You should have received a copy of the GNU General Public License version15* 2 along with this work; if not, write to the Free Software Foundation,16* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.17*18* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA19* or visit www.oracle.com if you need additional information or have any20* questions.21*/2223/* @test24* @bug 421773725* @clean NestedReplace A B C D26* @build NestedReplace27* @run main NestedReplace28* @summary Ensure that replacement objects can nominate their own replacements,29* so long as the replacement is not the same class as the30* just-replaced object.31*32*/3334import java.io.*;3536class A implements Serializable {37private static final long serialVersionUID = 1L;3839Object writeReplace() throws ObjectStreamException {40return new B();41}42}4344class B implements Serializable {45private static final long serialVersionUID = 1L;4647Object writeReplace() throws ObjectStreamException {48return new C();49}50}5152class C implements Serializable {53private static final long serialVersionUID = 1L;5455static int writeReplaceCalled = 0;5657Object writeReplace() throws ObjectStreamException {58writeReplaceCalled++;59return new C();60}6162Object readResolve() throws ObjectStreamException {63return new D();64}65}6667class D implements Serializable {68private static final long serialVersionUID = 1L;6970Object readResolve() throws ObjectStreamException {71throw new Error("readResolve() called more than once");72}73}7475public class NestedReplace {76public static void main(String[] args) throws Exception {77ByteArrayOutputStream bout;78ObjectOutputStream oout;79ByteArrayInputStream bin;80ObjectInputStream oin;81Object obj;8283bout = new ByteArrayOutputStream();84oout = new ObjectOutputStream(bout);85oout.writeObject(new A());86oout.flush();87bin = new ByteArrayInputStream(bout.toByteArray());88oin = new ObjectInputStream(bin);89obj = oin.readObject();9091if (! (obj instanceof D))92throw new Error("Deserialized object is of wrong class");93if (C.writeReplaceCalled != 1)94throw new Error("C.writeReplace() should only get called once");95}96}979899