2013-07-11 21:51:51 +02:00
|
|
|
package com.comphenix.protocol.reflect.cloning;
|
|
|
|
|
|
|
|
import java.io.ByteArrayInputStream;
|
|
|
|
import java.io.ByteArrayOutputStream;
|
|
|
|
import java.io.ObjectInputStream;
|
|
|
|
import java.io.ObjectOutputStream;
|
|
|
|
import java.io.Serializable;
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Represents a cloner that can clone any class that implements Serializable.
|
|
|
|
* @author Kristian Stangeland
|
|
|
|
*/
|
2013-07-17 15:49:35 +02:00
|
|
|
public class SerializableCloner implements Cloner {
|
2013-07-11 21:51:51 +02:00
|
|
|
|
2014-11-15 23:58:27 +01:00
|
|
|
@Override
|
|
|
|
public boolean canClone(Object source) {
|
|
|
|
if (source == null)
|
|
|
|
return false;
|
|
|
|
return source instanceof Serializable;
|
|
|
|
}
|
2013-07-11 21:51:51 +02:00
|
|
|
|
2014-11-15 23:58:27 +01:00
|
|
|
@Override
|
|
|
|
public Object clone(Object source) {
|
|
|
|
return SerializableCloner.clone((Serializable) source);
|
|
|
|
}
|
2013-07-11 21:51:51 +02:00
|
|
|
|
2014-11-15 23:58:27 +01:00
|
|
|
/**
|
|
|
|
* Clone the given object using serialization.
|
2015-06-17 20:25:39 +02:00
|
|
|
* @param <T> Type
|
2014-11-15 23:58:27 +01:00
|
|
|
* @param obj - the object to clone.
|
|
|
|
* @return The cloned object.
|
|
|
|
* @throws RuntimeException If we were unable to clone the object.
|
|
|
|
*/
|
2015-11-24 21:35:23 +01:00
|
|
|
@SuppressWarnings("unchecked")
|
|
|
|
public static <T extends Serializable> T clone(final T obj) {
|
|
|
|
try {
|
|
|
|
ByteArrayOutputStream out = new ByteArrayOutputStream();
|
|
|
|
ObjectOutputStream oout = new ObjectOutputStream(out);
|
2013-07-11 21:51:51 +02:00
|
|
|
|
2015-11-24 21:35:23 +01:00
|
|
|
oout.writeObject(obj);
|
|
|
|
ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(out.toByteArray()));
|
|
|
|
return (T) in.readObject();
|
|
|
|
} catch (Exception e) {
|
|
|
|
throw new RuntimeException("Unable to clone object " + obj + " (" + obj.getClass().getName() + ")", e);
|
|
|
|
}
|
|
|
|
}
|
2013-07-11 21:51:51 +02:00
|
|
|
}
|