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

前端 未结 3 1665
眼角桃花
眼角桃花 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: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);
    }
    

提交回复
热议问题