下面这段代码会抛出异常:
Exception in thread "main" java.lang.ClassCastException: test.Subclass2 cannot be cast to test.Subclass1
at test.LambdaTest.main(LambdaTest.java:17)
public class LambdaTest {
public static void main(String[] args) throws IOException, ClassNotFoundException {
ToLongFunction<B> fn1 = serde((ToLongFunction<B> & Serializable) B::value);
ToLongFunction<C> fn2 = serde((ToLongFunction<C> & Serializable) C::value);
fn1.applyAsLong(new B());
fn2.applyAsLong(new C()); // Line 17 -- exception here!
}
private static <T extends Serializable> T serde(T t) throws IOException, ClassNotFoundException {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
new ObjectOutputStream(bos).writeObject(t);
ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(bos
.toByteArray()));
return (T) ois.readObject();
}
}
class A {
public long value() {
return 0;
}
}
class B extends A { }
class C extends A { }
原因似乎是在序列化和反序列化后,fn1和fn2最终成为相同的类。这是JDK /编译器的错误还是我对lambda的序列化和反序列化有所遗漏?
main
中的序列化代码之前添加ToLongFunction<C> cc = (ToLongFunction<C>&Serializable) A :: value; cc.applyAsLong(new C());
,则会在fn1.applyAsLong
行上出现CCE。这似乎与@davidxxx的缓存建议一致。 - Andy Turner