Effective Java之保护性编写readObject方法(七十六)
生活随笔
收集整理的這篇文章主要介紹了
Effective Java之保护性编写readObject方法(七十六)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
readObject方法實際上相當于另一個公有的構造器,與其他構造器一樣,它也需要進行參數的有效性檢查與保護性拷貝。參考:Effective Java之必要時進行保護性拷貝(三十九)
原因很簡單,為了避免客戶端修改可變對象,服務器把可變對象的引用指向了客戶端找不到的地方,但是默認反序列化的過程把客戶端找不到的地方給了客戶端,給了客戶端修改的機會,導致了錯誤,readObject也應該完成構造器做的事。
private void readObject(ObjectInputStream s) throws IOException, ClassNotFoundException { s.defaultReadObject(); // Defensively copy our mutable components start = new Date(start.getTime()); end = new Date(end.getTime()); // Check that our invariants are satisfied if (start.compareTo(end) > 0) throw new InvalidObjectException(start +" after "+ end); } private void readObject(ObjectInputStream s) throws IOException, ClassNotFoundException {s.defaultReadObject();start = new Date(start.getTime());end = new Date(end.getTime());if (start.compareTo(end) > 0)throw new InvalidObjectException(start +" after "+ end); }總結
以上是生活随笔為你收集整理的Effective Java之保护性编写readObject方法(七十六)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Effective Java之考虑自定义
- 下一篇: Effective Java之对于实例控