[英]Can the Java Method object be compared by identity (ie. ==) or do I have to use equals()?
在Java中,可以通过标识(即。==)比较java.lang.reflect.Method
对象的实例,还是必须使用equals()?
The question does not refer to the difference between ==
and equals
in general, but refers to java.lang.reflect.Method
instances in particular. 问题并不是指一般的
==
和equals
之间的区别,而是特别指的是java.lang.reflect.Method
实例。
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. 这是一个合理的问题,因为可以证明每个
Method
只存在一个实例 - 类似于Class
对象,它们在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) 然而,这不是这种情况:两个
Method
对象可以是equal
,即使它们是不相同的 ,如在此示例中可以看出(它也做为比较Class
对象,要强调的是,这些确实是相同的)
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;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.