填坑:Externalizable、readUnshared

admin 2023年1月9日11:58:02评论36 views字数 2221阅读7分24秒阅读模式

一、Externalizable



它的源码如下

public interface Externalizable extends java.io.Serializable {    /**     * The object implements the writeExternal method to save its contents     * by calling the methods of DataOutput for its primitive values or     * calling the writeObject method of ObjectOutput for objects, strings,     * and arrays.     *     * @serialData Overriding methods should use this tag to describe     *             the data layout of this Externalizable object.     *             List the sequence of element types and, if possible,     *             relate the element to a public/protected field and/or     *             method of this Externalizable class.     *     * @param out the stream to write the object to     * @exception IOException Includes any I/O exceptions that may occur     */    void writeExternal(ObjectOutput out) throws IOException;

/** * The object implements the readExternal method to restore its * contents by calling the methods of DataInput for primitive * types and readObject for objects, strings and arrays. The * readExternal method must read the values in the same sequence * and with the same types as were written by writeExternal. * * @param in the stream to read data from in order to restore the object * @exception IOException if I/O errors occur * @exception ClassNotFoundException If the class for an object being * restored cannot be found. */ void readExternal(ObjectInput in) throws IOException, ClassNotFoundException;}
  • Externalizable继承自Serializable,使用Externalizable接口需要重写writeExternal以及readExternal方法,

  • 在writeExternal方法中,写入想要外部序列化的元素,有时我们不希望序列化那么多,可以使用这个接口,这个接口的writeExternal()和readExternal()方法可以指定序列化哪些属性;

  • Serializable序列化时不会调用默认的构造器,而Externalizable序列化时会调用默认构造器的,所以,使用Externalizable序列化,必须要声明一个无参构造,否则会报no valid constructor的异常。

  • 采用Externalizable无需产生序列化ID(serialVersionUID)~而Serializable接口则需要(serialVersionUID作用: 序列化时为了保持版本的兼容性,即在版本升级时反序列化仍保持对象的唯一性。 )

  • 相比较Serializable, Externalizable序列化、反序列更加快速,占用相比较小的内存

二、readUnshared



追溯到很久之前fox问的一个问题,readUnshared这个能反序列化利用吗?这个就让我有点懵逼,没见过这个,去本地期了一个demo,网上粘贴了一个readobject的demo 换成readUnshared  也弹了计算器

填坑:Externalizable、readUnshared

神奇,赶紧去搜了一下,我们都知道对象反序列化时会自动调用readObject方法,

Java ObjectInputStream中有两种类似的方法:readUnshared()和的readObject()

java.io.ObjectInputStream.readUnshared()方法从ObjectInputStream中读取“非共享”对象。此方法与readObject相同,不同之处在于它阻止对readObject和readUnshared的后续调用返回对通过此调用获得的反序列化实例的其他引用。具体而言

  • 如果调用readUnshared来反序列化反向引用(先前已写入流的对象的流表示),则抛出ObjectStreamException

  • 如果readUnshared成功返回,则后续尝试反序列化对readUnshared反序列化的流句柄的反向引用将导致抛出ObjectStreamException


大概就理解为,他们一样吧2333........




原文始发于微信公众号(赛博少女):填坑:Externalizable、readUnshared

  • 左青龙
  • 微信扫一扫
  • weinxin
  • 右白虎
  • 微信扫一扫
  • weinxin
admin
  • 本文由 发表于 2023年1月9日11:58:02
  • 转载请保留本文链接(CN-SEC中文网:感谢原作者辛苦付出):
                   填坑:Externalizable、readUnsharedhttps://cn-sec.com/archives/820313.html

发表评论

匿名网友 填写信息