1

I need to take the proxy instance created by Proxy.newProxyInstance as the key of a HashMap. I am not sure if it overwrites the equals and hashcode method of the Object. I am not sure if Object is suitable for that.

I checked the doc for hashcode method:

As much as is reasonably practical, the hashCode method defined by * class Object does return distinct integers for distinct * objects. (This is typically implemented by converting the internal * address of the object into an integer.

The hashcode of Object will change after the object instance is moved during GC. Is this right?

I got @NPE 's explanation:

The computation is performed the first time a hash code is required. To maintain consistency, the result is then stored in the object's header and is returned on subsequent calls to hashCode(). The caching is done outside this function.

So the hashcode of Object will not change.

I got this from Proxy Java Doc:

A method invocation on a proxy instance through one of its proxy interfaces will be dispatched to the invoke method of the instance's invocation handler, passing the proxy instance, a java.lang.reflect.Method object identifying the method that was invoked, and an array of type Object containing the arguments.

That's to say only those methods of its proxy interfaces will be involved for proxy action. equals and hashCode are reasonably excluded only if they are also in the interfaces.

So the proxy should not override Obeject's implementation.

Thanks

Community
  • 1
  • 1
Jacky
  • 8,619
  • 7
  • 36
  • 40

0 Answers0