此代码用于通过java序列化复制示例。它采用了传统的试一试的写作方法。是否可以更改为try with resources form?(代码中的deepconcreteprototype是一个普通的java对象)
/**
* Clone an instance through java serialization
* @return
*/
public DeepConcretePrototype deepCloneBySerializable() {
DeepConcretePrototype clone = null;
ByteArrayOutputStream byteArrayOutputStream = null;
ObjectOutputStream objectOutputStream = null;
ByteArrayInputStream byteArrayInputStream = null;
ObjectInputStream objectInputStream = null;
try {
//Output an instance to memory
byteArrayOutputStream = new ByteArrayOutputStream();
objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
objectOutputStream.writeObject(this);
objectOutputStream.flush();
//Read instance from memory
byteArrayInputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
objectInputStream = new ObjectInputStream(byteArrayInputStream);
clone = (DeepConcretePrototype)objectInputStream.readObject();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {
if (byteArrayOutputStream != null) {
try {
byteArrayOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (objectOutputStream != null) {
try {
objectOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (byteArrayInputStream != null) {
try {
byteArrayInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (objectInputStream != null) {
try {
objectInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return clone;
}
1条答案
按热度按时间6qftjkof1#
是的,您可以使用try with resources,但这有点棘手,因为
read
取决于write
. 一种方法是使用嵌套的try
: