'In Java Proxy, if i use an Object's method (like toString()),why it's method.invoke(this),not method.invoke(proxy) or other

In some code,like Mybatis,I saw the use of JDK-proxy. Example: org.apache.ibatis.logging.jdbc.ConnectionLogger:

public final class ConnectionLogger extends BaseJdbcLogger implements InvocationHandler {

  @Override
  public Object invoke(Object proxy, Method method, Object[] params)
      throws Throwable {
    try {
      if (Object.class.equals(method.getDeclaringClass())) {
        return method.invoke(this, params);
      }
    }
...
}
}

Maybe my code like this :

UserMapper user = getProxy(UserMapper.class);
user.hashCode()

If i use the method like hashCode() , it means i want to get the hashCode from the user, not user's Proxy.hashCode(), not invocationHandler.hashCode().And I really try to change the method like this,it happens an error:

if (Object.class.equals(method.getDeclaringClass())) {
        return method.invoke(proxy, params);
}

But why use 'this'(is this means an object from ConnectionLogger ?) Please tell me ,and sorry for my English ;)



Solution 1:[1]

You guessed right. The proxy address refers to the invocationhandler. Here is the test

@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

    if (Object.class.equals(method.getDeclaringClass())) {
        System.out.println(this);
        System.out.println(Integer.toHexString(System.identityHashCode(this)));
        System.out.println(Integer.toHexString(System.identityHashCode(proxy)));

        return method.invoke(this, args);
    }

    return "ddd";
}
            public static void main(String[] args) {
    InsertDataHandler c =new InsertDataHandler();
    Object L=c.getProxy();
 //   L.toString();
    System.out.println(L.toString());

}  

        E:\xzb\jdk\bin\java.exe 
         com.example.tenant.InsertDataHandler@728938a9
         728938a9
         21b8d17c
         com.example.tenant.InsertDataHandler@728938a9

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 zhi bo mis xue