1 46 package org.mr.core.util.byteable; 47 48 import java.io.ByteArrayInputStream ; 49 import java.io.ByteArrayOutputStream ; 50 import java.io.IOException ; 51 import java.io.ObjectInputStream ; 52 import java.io.ObjectOutputStream ; 53 import java.io.Serializable ; 54 55 60 public class ByteableSerializable implements Byteable{ 61 private Serializable serializable; 62 65 public String getByteableName() { 66 67 return "BSerializable"; 68 } 69 70 73 public void toBytes(ByteableOutputStream out) throws IOException { 74 byte[] arr = new byte[0]; 75 if(serializable != null){ 76 ByteArrayOutputStream underOut = new ByteArrayOutputStream (); 77 ObjectOutputStream objout = new ObjectOutputStream (underOut); 78 objout.writeObject(serializable); 79 objout.flush(); 80 arr = underOut.toByteArray(); 81 } 82 out.writeInt(arr.length); 83 out.write(arr); 84 85 } 86 87 90 public Byteable createInstance(ByteableInputStream in) throws IOException { 91 ByteableSerializable result = new ByteableSerializable(); 92 int length = in.readInt(); 93 if(length>0){ 94 byte[] arr = new byte[length]; 95 in.read(arr); 96 ByteArrayInputStream underin = new ByteArrayInputStream (arr); 97 ObjectInputStream objin = new ObjectInputStream (underin); 98 try { 99 result.setSerializable((Serializable )objin.readObject()); 100 } catch (ClassNotFoundException e) { 101 102 e.printStackTrace(); 103 } 104 } 105 return result; 106 } 107 108 111 public void registerToByteableRegistry() { 112 ByteableRegistry.registerByteableFactory(getByteableName() , this); 113 114 } 115 116 119 public Serializable getSerializable() { 120 return serializable; 121 } 122 125 public void setSerializable(Serializable serializable) { 126 this.serializable = serializable; 127 } 128 129 133 public static void register(){ 134 ByteableSerializable instance = new ByteableSerializable(); 135 instance.registerToByteableRegistry(); 136 } 137 } 138 | Popular Tags |