2012-04-08 4 views
10

가 여기에 자바 7 등 java.lang.reflect.Method.equals(Object obj)의 구현입니다 : getName() == other.getName() :이름 비교 (개체 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; 
} 

여기서 가장 흥미로운 부분은 메소드 이름의 비교입니다. 그 사람들은 java.lang.String을 반환하므로 자연스러운 질문은 참고 문헌 (==)으로 비교할 수 있는지의 여부입니다. 이 코드가 분명히 작동하는 동안 문제는 반사 지향 프레임 워크에서 버그의 원인이 될 수 있는지 여부입니다. 어떻게 생각해?

+0

getName()가 == other.getName()가'확인하고 싶어'쓴 하나에

보다 두'참조가 메모리에서 같은 객체를 참조 name' 여부보다는 여부 실제 문자열 값을 확인합니다. –

답변

9

Method 클래스의 name 속성을 직접 볼 때 흥미로운 점이 하나 있습니다.

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

문자열을 인턴함으로써 직접 참조를 비교할 수 있습니다. 어쩌면 String.intern()

+0

불행히도 이것은 모든 Java VM에 해당하지 않습니다. 나는. 안드로이드에서 Dalvik VM은 Method.getName에서 또는 적어도 항상은 아니지만 interned 문자열을 반환하지 않습니다. – x4u