Làm thế nào tôi có thể sắp xếp một cách thanh lịch một lambda?Làm thế nào để tuần tự hóa một lambda?
Ví dụ: mã bên dưới ném một số NotSerializableException
. Làm cách nào để khắc phục sự cố mà không cần tạo giao diện "giả" SerializableRunnable
?
public static void main(String[] args) throws Exception {
File file = Files.createTempFile("lambda", "ser").toFile();
try (ObjectOutput oo = new ObjectOutputStream(new FileOutputStream(file))) {
Runnable r =() -> System.out.println("Can I be serialized?");
oo.writeObject(r);
}
try (ObjectInput oi = new ObjectInputStream(new FileInputStream(file))) {
Runnable r = (Runnable) oi.readObject();
r.run();
}
}
Mặc dù điều này có thể (xem phần chọn lọc d trả lời), tất cả mọi người có lẽ nên suy nghĩ hai lần về thực sự làm điều này. Nó chính thức ["không khuyến khích"] (https://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html#serialization) và có thể có [nghiêm trọng] (http://stackoverflow.com/questions/25443655/khả năng-để-xoá-serial-hỗ trợ-cho-một-lambda) [bảo mật] (https://www.contrastsecurity.com/security-influencers/serialization-must-die-act-1-kryo) [ngụ ý] (https://www.contrastsecurity.com/security-influencers/serialization-must-die-act-2-xstream). – David