Why are multiple instances of a Method object intended for inherited methods

I found that classes with the standard equals method have different instances of the metaobject Method. Why is this so? At first glance, this does not look optimal, because the objects of the method are immutable.

class X {} Method defaultM = Object.class.getMethod("equals", Object.class) Method xMethod = X.class.getMethod("equals", Object.class) xMethod != defaultM xMethod.equals(defaultM) 
+6
source share
3 answers

Unfortunately, Method objects are not immutable. Since Java 2, Method extends AccessibleObject , which has a setAccessible(boolean) method.

Thus, not only methods have a mutable property, this flag has security implications that prohibit the sharing of Method objects.

Note that under the hood, Method objects exchange their common immutable state through a delegate object, so what you get from Class.getMethod is just a cheap external object consisting of this mutable flag and a link to the general representation of the canonical method.

+5
source

The following code prints false even for two Method objects that belong to the same Method in the same class:

 Method m1 = A.class.getMethod("equals", Object.class); Method m2 = A.class.getMethod("equals", Object.class); System.out.println(m1 == m2); 

Therefore, you should not expect one-dimensional behavior for Method objects that reference methods in two different classes.

+2
source

The Equals method of the object is not final; it must be overridden by your X class.

0
source

All Articles