java object 변환
Object to byte[]
public static byte[] toByteArray(Object obj) { byte[] bytes = null; ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutputStream oos = null; try { oos = new ObjectOutputStream(bos); oos.writeObject(obj); oos.flush(); bytes = bos.toByteArray(); } catch (IOException ex) { //TODO: Handle the exception ex.printStackTrace(); } finally { try { if(oos != null) oos.close(); if(oos != null) bos.close(); } catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
} } return bytes; } |
byte[] to Object 변환
public static Object toObject(byte[] bytes) { Object obj = null; try { ByteArrayInputStream bis = new ByteArrayInputStream(bytes); ObjectInputStream ois = new ObjectInputStream(bis); obj = ois.readObject(); } catch (IOException ex) { //TODO: Handle the exception ex.printStackTrace(); } catch (ClassNotFoundException ex) { //TODO: Handle the exception ex.printStackTrace(); } return obj; } |
참고할 사항은 Object 변환시 object은 serialize된 것이어야 변환시 문제가 없다.
public class AaaObj implements Serializable { /** * Value : {@value serialVersionUID} */ private static final long serialVersionUID = -5836025145746801447L;... } |