lucky-xin edited a comment on issue #54:
URL: 
https://github.com/apache/dubbo-hessian-lite/issues/54#issuecomment-986413418


   如果类定义了writeReplace方法,那么在创建JavaSerializer时会遍历类获取writeReplace方法
   ```java
    private Method _writeReplace;
   
       public JavaSerializer(Class cl, ClassLoader loader) {
           introspectWriteReplace(cl, loader);// 这里初始化_writeReplace
   
           if (_writeReplace != null)
               _writeReplace.setAccessible(true);
   }
   ```
   然后在序列化时就执行com.alibaba.com.caucho.hessian.io.JavaSerializer#writeObject方法,代码如下
   ```java
    @Override
       public void writeObject(Object obj, AbstractHessianOutput out)
               throws IOException {
           if (out.addRef(obj)) {
               return;
           }
   
           Class cl = obj.getClass();
   
           try {
               if (_writeReplace != null) {
                   Object repl;
   
                   if (_writeReplaceFactory != null)
                       repl = _writeReplace.invoke(_writeReplaceFactory, obj);
                   else
                       repl = _writeReplace.invoke(obj);
   
                   //Some class would return itself for wrapReplace, which 
would cause infinite recursion
                   //In this case, we could write the object just like normal 
cases
                   if (repl != obj) {
                       out.removeRef(obj);
   
                       out.writeObject(repl);
   
                       out.replaceRef(repl, obj);
   
                       return;
                   }
               }
           } catch (RuntimeException e) {
               throw e;
           } catch (Exception e) {
               // log.log(Level.FINE, e.toString(), e);
               throw new RuntimeException(e);
           }
   
           int ref = out.writeObjectBegin(cl.getName());
   
           if (ref < -1) {
               writeObject10(obj, out);
           } else {
               if (ref == -1) {
                   writeDefinition20(out);
                   out.writeObjectBegin(cl.getName());
               }
   
               writeInstance(obj, out);
           }
       }
   ```
   因为_writeReplace不为null,就执行writeReplace方法,然后替换对象


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscr...@dubbo.apache.org

For queries about this service, please contact Infrastructure at:
us...@infra.apache.org



---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscr...@dubbo.apache.org
For additional commands, e-mail: notifications-h...@dubbo.apache.org

Reply via email to