java.io.ByteArrayOutputStream baos = new ByteArrayOutputStream();
java.io.ObjectOutputStream oos;
try {
oos = new ObjectOutputStream(baos);
oos.writeObject(object);// object:要序列化的对象
} catch (IOException e) {}
将对象序列化到输出流里(可以是文件流、字节流等等)
从输入流中反序列化对象
java.io.ByteArrayInputStream bais =。。。;
java.io.ObjectInputStream ais;
try {
ais = new ObjectInputStream(bais);
Object bo = ais.readObject();
bs.setBo(bo);
}
序列化最重要的是反序列化时如何找到相关的class,这就涉及到反序列化的classloader机制。
ObjectInputStream通过resolveClass(ObjectStreamClass desc)方法去加载class,可以通过子类重写该方法加载class。Jsf中的反序列化重写了改方法,从当前线程加载。
ObjectInputStream
protected Class<?> resolveClass(ObjectStreamClass desc)
throws IOException, ClassNotFoundException
{
String name = desc.getName();
try {
//不是通过当前线程来加载类的,指定了classloader
return Class.forName(name, false, latestUserDefinedLoader());
} catch (ClassNotFoundException ex) {
Class cl = (Class) primClasses.get(name);
if (cl != null) {
return cl;
} else {
throw ex;
}
}
}
Jsf
public class ApplicationObjectInputStream extends ObjectInputStream {
public ApplicationObjectInputStream(){
super();
}
public ApplicationObjectInputStream(InputStream in) {
super(in);
}
protected Class<?> resolveClass(ObjectStreamClass desc) throws IOException, ClassNotFoundException {
return Class.forName(desc.getName(),true,
Thread.currentThread().getContextClassLoader());
}
}
使用子类反序列化
ais = new ApplicationObjectInputStream(bais);
Object bo = ais.readObject();
参见Externalizable介绍
http://www.360doc.com/content/10/0729/19/495229_42337853.shtml
http://wxg6203.iteye.com/blog/642598
当类反序列化他的属性时报ClassNotFoundException 可以通过readExternal方法来为他的属性类指定classloader。
java.lang.InstantiationException
当序列化类的某些方法中使用了直接new的 abstract class,会导致对象反序列化时报
java.lang.InstantiationException异常。原因未知。
如下代码导致MyClass不能被反序列化
MyClass implements Serializable {
Public void test(){
Hidden hidden=new Hidden() {
public Map nameValue() {
Map<String, String> deployMap = new HashMap<String, String>();
deployMap.put("name", ProcessForm.BO_DEPLOYMENT_ID);
deployMap.put("value", bussinessObjectContex
.getDeployment().getId());
return deployMap;
}
};
Hidden.xxxxx;
}
public abstract class Hidden{