0

I try to clone an Object by 1) shoving it into a ByteArrayOutputStream 2) assigning the stream to a byte array 3) reading the byte array by ByteArrayInputStream. However, this won't work as I can not assign the OutputStream to the byte array, the line will just not execute.

Apporoach is based Java Serializable Object to Byte Array

public Bank clone() {
        Bank objektKopie = null;
        byte[] byteKopie = null;
        ByteArrayOutputStream bo = new ByteArrayOutputStream();
        ObjectOutputStream oo = null;
        try {
            bo = new ByteArrayOutputStream();
            oo = new ObjectOutputStream(bo);
            oo.writeObject(this);
            oo.flush() ;
            byteKopie = bo.toByteArray(); // THIS WILL NOT HAPPEN
        } catch (Exception e) {
            System.out.println(e.getMessage());
        } finally {
            try {
               bo.close();
            } catch (IOException e) {
                System.out.println(e.getMessage());
            }
        }
        ByteArrayInputStream bi = new ByteArrayInputStream(byteKopie); // byteKopie IS STILL NULL
        ObjectInputStream oi = null;
        try {
            oi = new ObjectInputStream(bi);
            objektKopie = (Bank) oi.readObject();
        } catch (Exception e) { System.out.println(e.getMessage()); }
        return objektKopie;
    }
  • Are there any exceptions? By the way printing exception message only is not a good idea as you will loose the stacktrace. In this case you will have hard time determining if the exception comes from writing or reading the stream – Jayr May 29 '19 at 15:48
  • Indeed it does throw a serialization related error. I was using a mock object inside Bank class for unit testing. This is solved. –  May 30 '19 at 07:41

2 Answers2

0

Your code is throwing "NotSerializable" exception, your class Bank NEEDS to implement Serializable

vc73
  • 407
  • 3
  • 15
0

if dependencies are okay, GSON can do this fairly easily

kleopi
  • 460
  • 3
  • 13