实现Serializable的类是可以序列化的类。
所谓序列化就是将一个类序列化为字符串,在以后可以将这个字符串反序列化为对应的类。
当然,还可以考虑使用google的gson来进行对象序列化。
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
/**
* Created by cf on 17-6-15.
*/
public class Experiment implements Serializable {
protected final static Logger LOGGER = LoggerFactory.getLogger(Experiment.class);
private final static long serialVersionUID = 1;
private final static String CHARSET_NAME = "ISO-8859-1";
/**
* @brief 字符串反序列化为类
* @param serializedString
* @return
*/
public static Experiment deserialized(String serializedString){
try {
ByteArrayInputStream bis = new ByteArrayInputStream(
serializedString.getBytes(CHARSET_NAME));
ObjectInputStream ois = new ObjectInputStream(bis);
Experiment experiment = (Experiment) ois.readObject();
ois.close();
return experiment;
} catch (Exception e) {
LOGGER.info("deserialized error! serializedString is {}.", serializedString, e);
Experiment experiment = new Experiment();
return experiment;
}
}
/**
* @brief 类序列化为字符串
* @return
*/
public String serialized() {
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(this);
oos.flush();
String serializedString = baos.toString(CHARSET_NAME);
baos.close();
oos.close();
return serializedString;
} catch (Exception e) {
System.out.println(e);
LOGGER.info("serialized error!", e);
return "";
}
}
}