Are there any alternatives to implementing Clone in Java?

前端 未结 5 1233
醉酒成梦
醉酒成梦 2021-01-12 15:10

In my Java project, I have a vector of various types of Traders. These different types of traders are subclasses of the Trader class. Right now, I have a method that takes a

5条回答
  •  盖世英雄少女心
    2021-01-12 15:39

    One option: If you can make the objects serializable, you can serialize then deserialize it to make a copy, similar to what happens when passing an object over RMI.

    Quick copy method:

    public MyObject copy() {
        ObjectOutputStream oos = null;
        ObjectInputStream ois = null;
        try {
            ByteArrayOutputStream bos =  new ByteArrayOutputStream();
            oos = new ObjectOutputStream(bos);
            oos.writeObject(this);
            oos.flush();
            ByteArrayInputStream bin =
                new ByteArrayInputStream(bos.toByteArray());
            ois = new ObjectInputStream(bin);
            return (MyObject)ois.readObject();
        } catch(Exception e) {
            return null;
        } finally {
            try {
                oos.close();
                ois.close();
            } catch (Exception e) {
                return null;
            }
        }
    }
    

提交回复
热议问题