In Java, can instances of the java.lang.reflect.Method
object be compared by identity (ie. ==) or do I have to use equals()?
The question does not refer to the difference between ==
and equals
in general, but refers to java.lang.reflect.Method
instances in particular.
It is a reasonable question, because it could be justified to assume that there exists only one instance of each Method
- similar to Class
objects, which are created exactly once in the JVM.
However, this is not the case: Two Method
objects may be equal
, even though they are not identical, as can be seen in this example (it also does the comparison for Class
objects, to emphasize that these indeed are identical)
package stackoverflow;
import java.lang.reflect.Method;
public class MethodEquals
{
public static void main(String[] args) throws Exception
{
checkMethods();
checkClasses();
}
static void checkMethods() throws Exception
{
Method m0 = MethodEquals.class.getMethod("exampleMethod", int.class);
Method m1 = MethodEquals.class.getMethod("exampleMethod", int.class);
boolean identical = (m0 == m1);
boolean equal = m0.equals(m1);
System.out.println("Methods: "+(identical == equal)); // prints "false"
}
static void checkClasses() throws Exception
{
Class<?> c0 = Class.forName("stackoverflow.MethodEquals");
Class<?> c1 = Class.forName("stackoverflow.MethodEquals");
boolean identical = (c0 == c1);
boolean equal = c0.equals(c1);
System.out.println("Classes: "+(identical == equal)); // prints "true"
}
public float exampleMethod(int i)
{
return 42.0f;
}
}