11

这是java.lang.reflect.Method.equals(Object obj)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;
}

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

4

1 回答 1

10

当您直接查看 Method 类的 name 属性时,会发生一件有趣的事情。

 // This is guaranteed to be interned by the VM in the 1.4
// reflection implementation
private String              name;

所以通过实习字符串你可以直接比较参考。

更多关于String.intern()

于 2012-04-08T13:13:46.923 回答