// serialization/Blips.java// (c)2017 MindView LLC: see Copyright.txt// We make no guarantees that this code is fit for any purpose.// Visit http://OnJava8.com for more book information.// Simple use of Externalizable & a pitfallimport java.io.*;class Blip1 implements Externalizable {public Blip1() {System.out.println("Blip1 Constructor");}@Overridepublic void writeExternal(ObjectOutput out)throws IOException {System.out.println("Blip1.writeExternal");}@Overridepublic void readExternal(ObjectInput in)throws IOException, ClassNotFoundException {System.out.println("Blip1.readExternal");}}class Blip2 implements Externalizable {Blip2() {System.out.println("Blip2 Constructor");}@Overridepublic void writeExternal(ObjectOutput out)throws IOException {System.out.println("Blip2.writeExternal");}@Overridepublic void readExternal(ObjectInput in)throws IOException, ClassNotFoundException {System.out.println("Blip2.readExternal");}}public class Blips {public static void main(String[] args) {System.out.println("Constructing objects:");Blip1 b1 = new Blip1();Blip2 b2 = new Blip2();try(ObjectOutputStream o = new ObjectOutputStream(new FileOutputStream("Blips.serialized"))) {System.out.println("Saving objects:");o.writeObject(b1);o.writeObject(b2);} catch(IOException e) {throw new RuntimeException(e);}// Now get them back:System.out.println("Recovering b1:");try(ObjectInputStream in = new ObjectInputStream(new FileInputStream("Blips.serialized"))) {b1 = (Blip1)in.readObject();} catch(IOException | ClassNotFoundException e) {throw new RuntimeException(e);}// OOPS! Throws an exception://- System.out.println("Recovering b2:");//- b2 = (Blip2)in.readObject();}}/* Output:Constructing objects:Blip1 ConstructorBlip2 ConstructorSaving objects:Blip1.writeExternalBlip2.writeExternalRecovering b1:Blip1 ConstructorBlip1.readExternal*/
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。