无法访问实例字段和方法的 Java 8 lambda 无法反序列化
2022-09-03 15:37:37
在我看来,这是编译器或JVM中的一个错误,但也许有人有更好的解释。
下面的代码按原样运行良好,但是如果我取消注释直接使用“this”的第二个初始化,它不能反序列化对象(引发异常)。runnable
in.readObject()
public class TestClass implements Serializable {
String msg = "HEY!";
SerializableRunnable runnable;
public TestClass() {
TestClass self = this;
runnable = () -> self.say(); // uses a local copy of 'this'
// runnable = () -> this.say(); // uses 'this' directly
}
public void say() {
System.out.println(msg);
}
public static void main(String[] args) throws Exception {
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
try (ObjectOutputStream out = new ObjectOutputStream(buffer)) {
out.writeObject(new TestClass());
}
try (ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(buffer.toByteArray()))) {
TestClass s = (TestClass) in.readObject();
s.say();
}
}
}
interface SerializableRunnable extends Runnable, Serializable {
}
这是根本原因的堆栈跟踪:
java.lang.IllegalArgumentException: Invalid lambda deserialization
at j8test.TestClass.$deserializeLambda$(TestClass.java:1)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at java.lang.invoke.SerializedLambda.readResolve(SerializedLambda.java:230)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at java.io.ObjectStreamClass.invokeReadResolve(ObjectStreamClass.java:1104)
at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1810)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1351)
at java.io.ObjectInputStream.defaultReadFields(ObjectInputStream.java:1993)
at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:1918)
at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1801)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1351)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:371)
at j8test.TestClass.main(TestClass.java:30)
这是预期的行为吗?