Common Java serialization errors include: Class version conflict (InvalidClassException) No serializable superclass or interface declared (NotSerializableException) Access denied or illegal reflection serialized object (IllegalAccessException) Serialization of static fields is variable Or circular reference (StackOverflowException or inconsistent state)
Common Java serialization errors
Java serialization errors : An error that occurs when converting an object to or reconstructing an object from a binary stream. It is usually caused by the following reasons:
1. Class version conflict
InvalidClassException
error is thrown. class MyClass implements Serializable { private static final long serialVersionUID = 1L; private String name; // 省略其他代码... } // 序列化对象后修改了 MyClass MyClass myObject = new MyClass(); myObject.setName("John Doe"); // 将对象序列化到文件 FileOutputStream fos = new FileOutputStream("object.ser"); ObjectOutputStream oos = new ObjectOutputStream(fos); oos.writeObject(myObject); oos.close(); // 更改 MyClass 的 serialVersionUID MyClass.serialVersionUID = 2L; // 从文件中读取并反序列化对象 FileInputStream fis = new FileInputStream("object.ser"); ObjectInputStream ois = new ObjectInputStream(fis); MyClass deserializedObject = (MyClass) ois.readObject(); ois.close();
2. No serializable superclass or interface declared
NotSerializableException
. class NotSerializable { // ... } class MyClass extends NotSerializable implements Serializable { // ... }
3. Access Denied or Illegal Reflection
private
The writeObject
and readObject
methods. Reflective access to these methods results in IllegalAccessException
. class MyClass implements Serializable { private void writeObject(ObjectOutputStream oos) throws IOException { // ... } private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException { // ... } } // 使用反射调用 writeObject ObjectOutputStream oos = new ObjectOutputStream(new ByteArrayOutputStream()); oos.writeObject(myObject); Method m = MyClass.class.getDeclaredMethod("writeObject", ObjectOutputStream.class); m.setAccessible(true); m.invoke(myObject, oos);
4. Serialization of static fields
transient
). class MyClass implements Serializable { private static String staticField; private String instanceField; // ... }
5. Mutable or circular references
StackOverflowException
. Mutable objects can lead to inconsistent state. // 可变对象 class MyClass implements Serializable { private int mutableField; // ... } // 循环引用 class MyClass1 implements Serializable { private MyClass myClass2; class MyClass2 implements Serializable { private MyClass1 myClass1; } }
The above is the detailed content of What are common Java serialization errors?. For more information, please follow other related articles on the PHP Chinese website!