Enum类是Serializable,所以没有问题序列化对象与枚举。另一种情况是类有java.util.Optional类的字段。在这种情况下,抛出以下异常:java.io.NotSerializableException:java.util.Optional
如何处理这样的类,如何将它们序列化?是否可以将此类对象发送到远程EJB或通过RMI?
这是例子:
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.Optional;
import org.junit.Test;
public class SerializationTest {
static class My implements Serializable {
private static final long serialVersionUID = 1L;
Optional value = Optional.empty();
public void setValue(Integer i) {
this.i = Optional.of(i);
}
public Optional getValue() {
return value;
}
}
//java.io.NotSerializableException is thrown
@Test
public void serialize() {
My my = new My();
byte[] bytes = toBytes(my);
}
public static byte[] toBytes(T reportInfo) {
try (ByteArrayOutputStream bstream = new ByteArrayOutputStream()) {
try (ObjectOutputStream ostream = new ObjectOutputStream(bstream)) {
ostream.writeObject(reportInfo);
}
return bstream.toByteArray();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}