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

whe*_*eph 10 java reflection

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;
}
Run Code Online (Sandbox Code Playgroud)

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

小智 10

直接查看Method类的name属性时有一点很有趣.

 // This is guaranteed to be interned by the VM in the 1.4
// reflection implementation
private String              name;
Run Code Online (Sandbox Code Playgroud)

所以通过实习String你可以直接比较参考.

有关String.intern()的更多信息