The anonymous inner class calls method parameters, the method parameter object has changed, but the anonymous inner class reference has not changed

The anonymous inner class calls method parameters, the method parameter object has changed, but the anonymous inner class reference has not changed

public void startServer(final LanServerBean.Builder builder){
        Log.i(TAG, "quqx_startServer: builder="+builder.hashCode());
        HttpServerRequestCallback callback = new HttpServerRequestCallback() {
            @Override
            public void onRequest(AsyncHttpServerRequest request, AsyncHttpServerResponse response) {
                Log.e(TAG, "quqx_onRequest: builer=" + builder.hashCode());
                ......
            }
        };
  
        mHttpServer.get("/", callback);
        ......
    }

Problem: As in the above code, the startServer() method is called for the first time, and the two logs show that the objects of the builder are the same. Then, when the method is called, the printing shows that the objects of the builder are inconsistent. The printing at quqx_onRequest is always the first referenced object .

Analysis: callback is the implementation class of the interface, which is held by mHttpServer. When mHttpServer remains unchanged, the content in the callback will not change.

Solution:

public void startServer(final LanServerBean.Builder builder){
            Log.i(TAG, "quqx_startServer: builder="+builder.hashCode());
            HttpServerRequestCallback callback = new HttpServerRequestCallback() {
                @Override
                public void onRequest(AsyncHttpServerRequest request, AsyncHttpServerResponse response) {
                    Log.e(TAG, "quqx_onRequest: builer=" + builder.hashCode());
                    ......
                }
            };
      
        	mHttpServer = new AsyncHttpServer();  //新new一个对象解决问题
            mHttpServer.get("/", callback);
            ......
        }

Guess you like

Origin blog.csdn.net/weixin_41820878/article/details/101075288