Đây là việc thực hiện các java.lang.reflect.Method.equals(Object obj)
như của Java 7:Tên so sánh trong 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;
}
Phần thú vị nhất ở đây là so sánh các tên phương pháp: getName() == other.getName()
. Những trở lại java.lang.String
và do đó một câu hỏi tự nhiên là liệu nó có hợp lệ để so sánh chúng với tham chiếu (==
). Mặc dù mã này rõ ràng là hoạt động, câu hỏi đặt ra là liệu nó có thể là một nguồn của các lỗi trong các khung định hướng phản chiếu hay không. Bạn nghĩ sao?
Có lẽ một trong những người đã viết 'getName() == other.getName() 'muốn kiểm tra xem hai' name' tài liệu tham khảo đề cập đến cùng một đối tượng trong bộ nhớ hay không, chứ không phải là kiểm tra các giá trị chuỗi thực tế. –