存储到memcached的所有对象都必须实现Serializable接口。今天修改系统缓存实现,从系统内部的Cache转到memcached。在转换过程中出现了内部类因为不能序列化导致设置缓存失败。写了以下的测试代码测试内部类的序列化:
[code]
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import junit.framework.TestCase;
public class SerializableInnerClassTest extends TestCase
{
class Person implements Serializable{
String name;
String password;
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public String getPassword()
{
return password;
}
public void setPassword(String password)
{
this.password = password;
}
}
public void testSerializable(){
ByteArrayOutputStream out = new ByteArrayOutputStream();
ObjectOutputStream oos;
try
{
oos = new ObjectOutputStream(out);
oos.writeObject(new Person());
oos.close();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
assertTrue(out.toByteArray().length > 0);
}
}
[/code]
这个测试跑的话将会抛出java.io.NotSerializableException异常。
后查找资料,发现内部类改成静态内部类后,序列化成功。
这是咋会事情呢?静态内部类和非静态内部类在序列化过程中有什么不同呢?
[code]
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import junit.framework.TestCase;
public class SerializableInnerClassTest extends TestCase
{
class Person implements Serializable{
String name;
String password;
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public String getPassword()
{
return password;
}
public void setPassword(String password)
{
this.password = password;
}
}
public void testSerializable(){
ByteArrayOutputStream out = new ByteArrayOutputStream();
ObjectOutputStream oos;
try
{
oos = new ObjectOutputStream(out);
oos.writeObject(new Person());
oos.close();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
assertTrue(out.toByteArray().length > 0);
}
}
[/code]
这个测试跑的话将会抛出java.io.NotSerializableException异常。
后查找资料,发现内部类改成静态内部类后,序列化成功。
这是咋会事情呢?静态内部类和非静态内部类在序列化过程中有什么不同呢?