java.lang.reflect.Method.equals中的名称比较(对象obj)

java.lang.reflect.Method.equals中的名称比较(对象obj),java,reflection,Java,Reflection,以下是java 7的java.lang.reflect.Method.equals(objectobj)的实现: /** * 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

以下是java 7的
java.lang.reflect.Method.equals(objectobj)
的实现:

/**
 * 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;
}
/**
*将此{@code Method}与指定的对象进行比较。退换商品
*如果对象相同,则为true。两个{@code方法}如果
*它们由同一类声明,并且具有相同的名称
*以及形式参数类型和返回类型。
*/
公共布尔等于(对象obj){
if(obj!=null&&obj instanceof Method){
方法其他=(方法)obj;
if((getDeclaringClass()==other.getDeclaringClass())
&&(getName()==其他.getName()){
如果(!returnType.equals(other.getReturnType()))
返回false;
/*避免不必要的克隆*/
Class[]params1=参数类型;
Class[]params2=其他.parameterTypes;
if(params1.length==params2.length){
对于(int i=0;i

这里最有趣的部分是方法名的比较:
getName()==other.getName()
。它们返回
java.lang.String
,因此一个自然的问题是通过引用比较它们是否有效(
=
)。虽然这段代码显然有效,但问题是它是否会成为面向反射的框架中的bug源。您觉得怎么样?

当您直接查看Method类的name属性时,有一件事很有趣

 // This is guaranteed to be interned by the VM in the 1.4
// reflection implementation
private String              name;
所以通过插入字符串,您可以直接比较引用


更多关于

的信息可能是编写
getName()==other.getName()
的人想要检查两个
name
引用是否引用了内存中的同一个对象,而不是检查实际的字符串值。不幸的是,并非所有Java虚拟机都是如此。也就是说,Android上的Dalvik VM不会从Method.getName返回内部字符串,或者至少不总是这样。