Here’s the implementation of java.lang.reflect.Method.equals(Object obj) as of Java 7:
/**
* Compares this {@code Method} against the specified object. Returns
* true if the objects are the same. Two {@code Methods} are the same if
* they were declared by the same class and have the same name
* and formal parameter types and return type.
*/
public boolean equals(Object obj) {
if (obj != null && obj instanceof Method) {
Method other = (Method)obj;
if ((getDeclaringClass() == other.getDeclaringClass())
&& (getName() == other.getName())) {
if (!returnType.equals(other.getReturnType()))
return false;
/* Avoid unnecessary cloning */
Class<?>[] params1 = parameterTypes;
Class<?>[] params2 = other.parameterTypes;
if (params1.length == params2.length) {
for (int i = 0; i < params1.length; i++) {
if (params1[i] != params2[i])
return false;
}
return true;
}
}
}
return false;
}
The most interesting part here is comparison of method names: getName() == other.getName(). Those return java.lang.String and hence a natural question is whether it’s valid to compare them by references (==). While this code obviously works the question is whether it can be a source of bugs in reflection-oriented frameworks. What do you think?
One thing interesting when you look directly on name attribute of Method class.
So by interning String you can directly compare reference.
More on String.intern()