io

Externalize arbitrary objects

public static byte[][] serializeObject(Externalizable object) throws Exception {
  ByteArrayOutputStream baos = null;
  ObjectOutputStream oos = null;
  byte[][] res = new byte[2][];
  
  try {
   baos = new ByteArrayOutputStream();
   oos = new ObjectOutputStream(baos);
   
   object.writeExternal(oos);
   oos.flush();
   
   res[0] = object.getClass().getName().getBytes();
   res[1] = baos.toByteArray();
  
  } catch (Exception ex) {
   throw ex;
  } finally {
   try {
    if(oos != null)
     oos.close();
   } catch (Exception e) {
    e.printStackTrace();
   }
  }
  
  return res;
 }
 
public static Externalizable deserializeObject(byte[][] rowObject) throws Exception {
  ObjectInputStream ois = null;
  String objectClassName = null;
  Externalizable res = null;
  
  try {
   
   objectClassName = new String(rowObject[0]);
   byte[] objectBytes = rowObject[1];
   
   ois = new ObjectInputStream(new ByteArrayInputStream(objectBytes));
   
   Class objectClass = Class.forName(objectClassName);
   res = (Externalizable) objectClass.newInstance();
   res.readExternal(ois);
  
  } catch (Exception ex) {
   throw ex;
  } finally {
   try {
    if(ois != null)
     ois.close();
   } catch (Exception e) {
    e.printStackTrace();
   }
   
  }
  
  return res;
  
 }
 

Related Article:

Byron Kiourtzoglou

Byron is a master software engineer working in the IT and Telecom domains. He is an applications developer in a wide variety of applications/services. He is currently acting as the team leader and technical architect for a proprietary service creation and integration platform for both the IT and Telecom industries in addition to a in-house big data real-time analytics solution. He is always fascinated by SOA, middleware services and mobile development. Byron is co-founder and Executive Editor at Java Code Geeks.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button