How private writeObject method of Serializable object called by object of ObjectOutputStream

前端 未结 3 1663
眼角桃花
眼角桃花 2020-12-10 10:22

When i run this demo it\'s call TestBean\'s writeObject method which is private

How is it possible ?

Here is the Code:

import j         


        
相关标签:
3条回答
  • 2020-12-10 10:26

    The virtual machine will automatically check to see if either method is declared during the corresponding method call. The virtual machine can call private methods of your class whenever it wants but no other objects can. Thus, the integrity of the class is maintained and the serialization protocol can continue to work as normal. The serialization protocol is always used the same way, by calling either ObjectOutputStream.writeObject() or ObjectInputStream.readObject(). So, even though those specialized private methods are provided, the object serialization works the same way as far as any calling object is concerned.

    You will get more about from this article:

    Discover the secrets of the Java Serialization API

    0 讨论(0)
  • 2020-12-10 10:28

    It uses reflection. private and public are not security measures. That is only a contract for class users.

    0 讨论(0)
  • 2020-12-10 10:30

    If your serializable object has any writeObject method, it will be called otherwise the defaultWriteObject method will be called.

    The private method calling is possible using the reflection. If you see the source code of ObjectOutputStream Class in that method writeSerialData, the code below answers your question.

    if (slotDesc.hasWriteObjectMethod()) {
     // through reflection it will call the Serializable objects writeObject method
    } else {
    // the below is the same method called by defaultWriteObject method also.
    writeSerialData(obj, desc);
    }
    
    0 讨论(0)
提交回复
热议问题