11

Java7以降の実装は次のjava.lang.reflect.Method.equals(Object obj)とおりです。

/**
 * 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 属性を直接見ると興味深いことが 1 つあります。

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

したがって、 String をインターンすることにより、参照を直接比較できます。

String.intern()の詳細

于 2012-04-08T13:13:46.923 に答える