Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Name comparison in java.lang.reflect.Method.equals(Object obj)

Tags:

People also ask

What does Object obj mean in Java?

For more on override of equals(Object obj) method refer – Overriding equals method in Java. Note: It is generally necessary to override the hashCode() method whenever this method is overridden, so as to maintain the general contract for the hashCode method, which states that equal objects must have equal hash codes.

How do you compare objects in Java?

In Java, the == operator compares that two references are identical or not. Whereas the equals() method compares two objects. Objects are equal when they have the same state (usually comparing variables). Objects are identical when they share the class identity.

What is equals method in Object class Java?

The equals method for class Object implements the most discriminating possible equivalence relation on objects; that is, for any non-null reference values x and y, this method returns true if and only if x and y refer to the same object (x == y has the value true).

How do you make two objects equal in Java?

Java determines equality with the equals(Object o) method - two objects a and b are equal iff a. equals(b) and b. equals(a) return true . These two objects will be equal using the base Object definition of equality, so you don't have to worry about that.


Here's the implementation of java.lang.reflect.Method.equals(Object obj) as of 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;
}

The most interesting part here is comparison of method names: getName() == other.getName(). Those return java.lang.String and hence a natural question is whether it's valid to compare them by references (==). While this code obviously works the question is whether it can be a source of bugs in reflection-oriented frameworks. What do you think?